﻿/*-------------------------------------------------------------------------
* 命名空间: SiliconSelect.BLL/SiliconBLL
* 类       名: SiliconBLL
* 功      能:  TD
* 时      间:  2023/6/20 16:26:06
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using HslCommunication;
using HslCommunication.Secs.Types;
using SiliconSelect.Base;
using SiliconSelect.Common;
using SiliconSelect.DAL;
using SiliconSelect.DAL.DataEntity;
using SiliconSelect.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata.Ecma335;
using System.Windows;

namespace SiliconSelect.BLL
{
    public class LocalDataAccess
    {
        #region 1. 查询数据

        /// <summary>
        /// 检测用户名和密码是否正确.
        /// </summary>
        /// <param name="unsername"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static DataResult<UserEntity> CheckUserInfo(string unsername, string password)
        {
            DataResult<UserEntity> result = new DataResult<UserEntity>();
            try
            {
                string sql = $"select * from {TableNames.UserTb} where username=@username COLLATE Latin1_general_CS_AS " +
                    $"and password=@password";
                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@username",SqlDbType.VarChar){Value = unsername},
                    new SqlParameter ("@password",SqlDbType.VarChar){Value = password}
                };
                DataTable table = new DataTable();
                table = DataAccess.GetDataTables(sql, parameters);

                if (table.Rows.Count <= 0)
                {
                    result.Message = "用户名或密码不正确!";
                    return result;
                }

                UserEntity user = (from q in table.AsEnumerable()
                                   select new UserEntity
                                   {
                                       Username = q.Field<string>("username"),
                                       Password = q.Field<string>("password"),
                                       Role = q.Field<string>("role")
                                   }).ToList()[0];
                result.Data = user;
                result.State = true;

            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取用户信息表的数据列表
        /// </summary>
        /// <returns></returns>
        public static DataResult<List<UserEntity>> GetUserList()
        {
            DataResult<List<UserEntity>> result = new DataResult<List<UserEntity>>();
            string tableName = TableNames.UserTb;
            try
            {
                string sql = $"Select *  from {tableName} Order By [Username]";
                DataTable? table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者表中无数据";
                    return result;
                }

                List<UserEntity> userList = (from q in table.AsEnumerable()
                                             select new UserEntity
                                             {
                                                 Username = q.Field<string>("Username"),
                                                 Password = q.Field<string>("Password"),
                                                 Role = q.Field<string>("Role"),
                                                 CreateBy = q.Field<string>("CreateBy"),
                                                 CreateTime = q.Field<string>("CreateTime"),
                                                 LastLoginTime = q.Field<string>("LastLoginTime")
                                             }).ToList();
                result.Data = userList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取当前的工作信息表的信息对应的实体类.
        /// </summary>
        /// <returns></returns>
        public static DataResult<WorkingInfoEntity> GetWorkingInfo()
        {
            DataResult<WorkingInfoEntity> result = new DataResult<WorkingInfoEntity>();
            string tableName = TableNames.WorkingInfoTb;
            try
            {
                string sql = $"select * from {tableName}";
                DataTable table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是表中无数据";
                    return result;
                }
                WorkingInfoEntity workingInfo = (from q in table.AsEnumerable()
                                                 select new WorkingInfoEntity
                                                 {
                                                     FlowerNumber = q.Field<string>("FlowerNumber"),
                                                     ProductionDate = q.Field<string>("ProductionDate"),
                                                     CutNumber = q.Field<string>("CutNumber"),
                                                     CrystalNumber = q.Field<string>("CrystalNumber"),
                                                     TheoryCounts = q.Field<string>("TheoryCounts"),
                                                     TotalCountFromPc = q.Field<string>("TotalCountFromPc"),
                                                     PositionNumber = q.Field<string>("PositionNumber"),
                                                     ProductionLot = q.Field<string>("ProductionLot"),
                                                     ProductionRecipe = q.Field<string>("ProductionRecipe"),
                                                     RecipeImportDir = q.Field<string>("RecipeImportDir"),
                                                     RecipeImportFile = q.Field<string>("RecipeImportFile"),
                                                     LastCrystalNumber = q.Field<string>("LastCrystalNumber"),
                                                 }).ToList()[0];
                result.Data = workingInfo;
                result.State = true;

            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取屏蔽状态对应的实体类的列表,使用的时候还要过滤一下,只选择为true的情况.
        /// </summary>
        /// <returns></returns>
        public static DataResult<List<ModuleShieldStateEntity>> GetModuleShieldState()
        {
            DataResult<List<ModuleShieldStateEntity>> result = new DataResult<List<ModuleShieldStateEntity>>();
            try
            {
                string tableName = TableNames.ModuleShieldStateTb;
                string sql = $"select * from {tableName}";
                DataTable table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    return result;
                }
                List<ModuleShieldStateEntity> moduleShieldStateList = (from q in table.AsEnumerable()
                                                                       select new ModuleShieldStateEntity
                                                                       {
                                                                           ModuleName = q.Field<string>("ModuleName"),
                                                                           IsShielded = q.Field<bool>("IsShielded")
                                                                       }).ToList();
                result.Data = moduleShieldStateList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取所有从站配置的列表
        /// </summary>
        /// <returns></returns>
        public static DataResult<List<SlaveSettingEntity>> GetSlaveSettings()
        {
            DataResult<List<SlaveSettingEntity>> result = new DataResult<List<SlaveSettingEntity>>();
            string tableName = TableNames.SlaveSettingTb;
            try
            {
                string sql = $"select * from {tableName} order by Id ";
                DataTable table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    return result;
                }
                List<SlaveSettingEntity> slaveSettingList = (from q in table.AsEnumerable()
                                                             select new SlaveSettingEntity
                                                             {
                                                                 SlaveName = q.Field<string>("SlaveName"),
                                                                 SlaveIp = q.Field<string>("SlaveIp"),
                                                                 SlavePort = q.Field<int>("SlavePort"),
                                                             }).ToList();
                result.Data = slaveSettingList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 根据晶棒编号去获取晶棒的统计信息. 
        /// </summary>
        /// <param name="crystalNumber"></param>
        /// <returns></returns>
        public static DataResult<List<CrystalLevelCountEntity>> GetCrystalLevelCount(string? crystalNumber, string direction = "Asc")
        {
            DataResult<List<CrystalLevelCountEntity>> result = new DataResult<List<CrystalLevelCountEntity>>();
            string tableName = TableNames.CrystalLevelCountTb;
            try
            {
                string sql = $"select * from {tableName} where CrystalNumber=@CrystalNumber COLLATE Latin1_general_CS_AS order by LevelIndex + 1 {direction} ";
                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@CrystalNumber",SqlDbType.VarChar){Value = crystalNumber},
                };
                DataTable table = DataAccess.GetDataTables(sql, parameters);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    return result;
                }
                List<CrystalLevelCountEntity> crystalLevelCountList = (from q in table.AsEnumerable()
                                                                       select new CrystalLevelCountEntity()
                                                                       {
                                                                           CrystalNumber = q.Field<string>("CrystalNumber"),
                                                                           LevelIndex = q.Field<int>("LevelIndex"),
                                                                           LevelType = q.Field<string>("LevelType"),
                                                                           Count = q.Field<string>("Count")
                                                                       }).ToList();
                result.Data = crystalLevelCountList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        /// <summary>
        /// 这里首先是根据工单去加载的时候获取的内容.如果这个晶棒还没有保存到数据库中.
        /// 如果已经存在于数据库怎么办呢? 就要将这个数据删除.这个只是在导入工单的时候
        /// 使用,导入工单的时候.这个数据和首页显示的那个数据是同时获取的.
        /// </summary>
        /// <returns></returns>
        public static DataResult<List<DetectedLevelEntity>> GetRecipeDetectedLevel(string PordutionRecipePathUsed)
        {
            DataResult<List<DetectedLevelEntity>> result = new DataResult<List<DetectedLevelEntity>>();
            try
            {
                string recipeFileName = Path.GetFileName(PordutionRecipePathUsed);
                GlobalValues.ProductionRecipeName = recipeFileName;
                DataTable table = ExcelHelper.ExcelToDataTableByStreamReader(PordutionRecipePathUsed, rowCount: -1, colCount: 5, hasTitle: true);
                if (table.Rows.Count == 0)
                {
                    result.State = true;
                    return result;
                }
                List<DetectedLevelEntity> detectedLevelList = (from q in table.AsEnumerable()
                                                               select new DetectedLevelEntity
                                                               {
                                                                   DetectedRecipe = recipeFileName,
                                                                   Level = int.Parse(q.Field<string>(DetectedLevelHeader.Header01)!),
                                                                   IsUsed = q.Field<string>(DetectedLevelHeader.Header02)?.ToUpper() == "TRUE",
                                                                   LevelType = q.Field<string>(DetectedLevelHeader.Header03),
                                                                   TypeDescription = q.Field<string>(DetectedLevelHeader.Header04),
                                                                   BoxesInto = q.Field<string>(DetectedLevelHeader.Header05)!.Trim('\"')
                                                               }).ToList();
                result.Data = detectedLevelList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        // 获取工单上的检测标准,默认是按照从第24行开始的.
        public static DataResult<List<List<string>>> GetRecipeDectectedRuleContent(string PordutionRecipePathUsed)
        {
            DataResult<List<List<string>>> result = new DataResult<List<List<string>>>();
            try
            {
                string recipeFileName = Path.GetFileName(PordutionRecipePathUsed);
                List<List<string>> resList = ExcelHelper.ExcelToListStringByStreamReader(PordutionRecipePathUsed, rowCount: -1, ColCount: -1, hasTitle: true);
                result.Data = resList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }



        // 获取所有料盒对应的数据信息(料盒状态)
        public static DataResult<List<BoxesStateEntity>> GetBoxesStates()
        {
            DataResult<List<BoxesStateEntity>> result = new DataResult<List<BoxesStateEntity>>();
            string tableName = TableNames.BoxesStateTb;
            try
            {
                string sql = $"select * from {tableName} order by  BoxNumber + 1";
                DataTable table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    return result;
                }
                List<BoxesStateEntity> boxesStateList = (from q in table.AsEnumerable()
                                                         select new BoxesStateEntity
                                                         {
                                                             BoxNumber = q.Field<string>("BoxNumber"),
                                                             LevelType = q.Field<string>("LevelType"),
                                                             Count = q.Field<string>("Count"),
                                                             CountMax = q.Field<string>("CountMax")
                                                         }).ToList();
                result.Data = boxesStateList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        public static DataResult<List<AlarmSettingEntity>> GetAlarmSettings()
        {
            DataResult<List<AlarmSettingEntity>> result = new DataResult<List<AlarmSettingEntity>>();
            string tableName = TableNames.AlarmSettingTb;
            DataTable table;
            List<AlarmSettingEntity> alarmList = new List<AlarmSettingEntity>();
            try
            {
                string sql = $"Select * from {tableName} Order By Id";
                table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count > 0)
                {
                    alarmList = (from q in table.AsEnumerable()
                                 select new AlarmSettingEntity()
                                 {
                                     Id = q.Field<int>("Id"),
                                     AlarmCode = q.Field<string>("AlarmCode"),
                                     Content = q.Field<string>("Content"),
                                     SolutionHelp = q.Field<string>("SolutionHelp")
                                 }).ToList();
                }
                result.Data = alarmList;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        // 获取报警信息的实体类(料盒状态)
        public static DataResult<List<AlarmRecordEntity>> GetAlarmRecord(string orderBy = "Id", bool isDesc = false, int dataCount = 200, string queryFeild = "", string queryVal = "")
        {
            DataResult<List<AlarmRecordEntity>> result = new DataResult<List<AlarmRecordEntity>>();
            try
            {
                string tableName = TableNames.AlarmRecordTb;
                string direction = isDesc ? "Desc" : "Asc";
                DataTable table;
                if (queryFeild == "" || queryVal == "")
                {
                    string sql = $"select Top {dataCount} * from {tableName} Order By {orderBy} {direction};";
                    table = DataAccess.GetDataTables(sql, null);
                }
                else
                {
                    string sql = $"select Top {dataCount} * from {tableName} where [{queryFeild}] = @{queryVal} Order By {orderBy} {direction};";
                    SqlParameter[] parameters = new SqlParameter[]
                     {
                        new SqlParameter($"@{queryFeild}",SqlDbType.VarChar){Value = queryVal},
                     };
                    table = DataAccess.GetDataTables(sql, parameters);
                }

                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    return result;
                }
                List<AlarmRecordEntity> alarmList = (from q in table.AsEnumerable()
                                                     select new AlarmRecordEntity
                                                     {
                                                         Id = q.Field<int>("Id"),
                                                         AlarmCode = q.Field<string>("AlarmCode"),
                                                         Content = q.Field<string>("Content"),
                                                         SolutionHelp = q.Field<string>("SolutionHelp"),
                                                         CreateTime = q.Field<string>("CreateTime"),
                                                     }).ToList();
                result.Data = alarmList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        public static DataResult<List<AlarmRecordEntity>> GetAlarmMainShow(string orderBy = "Id", bool isDesc = false)
        {
            DataResult<List<AlarmRecordEntity>> result = new DataResult<List<AlarmRecordEntity>>();
            try
            {
                string tableName = TableNames.AlarmMainShowTb;
                string direction = isDesc ? "Desc" : "Asc";
                DataTable table;
                string sql = $"select * from {tableName} Order By {orderBy} {direction};";
                table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    List<AlarmRecordEntity> alarmList2 = new List<AlarmRecordEntity>();
                    result.Data = alarmList2;
                    result.State = true;
                    return result;
                }
                List<AlarmRecordEntity> alarmList = (from q in table.AsEnumerable()
                                                     select new AlarmRecordEntity
                                                     {
                                                         Id = q.Field<int>("Id"),
                                                         AlarmCode = q.Field<string>("AlarmCode"),
                                                         Content = q.Field<string>("Content"),
                                                         SolutionHelp = q.Field<string>("SolutionHelp"),
                                                         CreateTime = q.Field<string>("CreateTime"),
                                                     }).ToList();
                result.Data = alarmList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        public static DataResult<DataTable> GetDatatableResultSummaryByCrystal(string crystalNumber, List<string> queryFields, List<string> queryVals, string orderBy = "Id", bool isDesc = false)
        {
            DataResult<DataTable> result = new DataResult<DataTable>();
            try
            {
                string tableName = TableManager.GetTableNameByCrystalNumber(crystalNumber);
                string direction = isDesc ? "Desc" : "Asc";
                DataTable table;
                if (queryFields.Count == 1 && queryVals.Count == 1)
                {
                    string sql = $"select  [DetectedTime] ,[ProductionDate],[WaferId],[CutNumber],[CrystalNumber],[PositionNumber]," +
                        $"[ProductionLot],[FlowerNumber],[DetectionRecipe],[DetectedLevel],[LevelType]      ,[TypeDescription]     ,[BoxNumber],[ThicknessAver],[TTV]     ,[LineTraceMax] ,[Warping]  ,[ResistivityAver] ," +
                        $"[ResistivityMax] ,[ResistivityMin] ,[LengthXMax],[LengthXMin],[LengthYMax],[LengthYMin] ,[LengthMax] ,[LengthMin] ,[LengthX],[LengthY],[DiagonalLeftStart],[DialonalRightStart]," +
                        $"[ChamferMax],[ChamferMin],[UpDownParallel]  ,[LeftRightParallel],[SquareLineMax] ,[SquareLineMin],[VerticalAngleMax],[VerticalAngleMin]      ,[LeftTopCharmfer]," +
                        $"[RightTopCharmfer],[LeftBottomCharmfer],[RightBottomCharmfer],[LeftTopAngle],[RightTopAngle],[LeftBottomAngle],[RightBottomAngle],[FrontEdgeBreakExist],[FrontEdgeBreakNum]," +
                        $"[FrontEdgeBreakArea],[BackEdgeBreakExist],[BackEdgeBreakNum],[BackEdgeBreakArea],[LeftEdgeBreakExist],[LeftEdgeBreakNum],[LeftSurfaceBreakExist],[LeftSurfaceBreakNum]," +
                        $"[RightEdgeBreakExist],[RightEdgeBreakNum],[RightSurfaceBreakExist],[RightSurfaceBreakNum],[ThicknessMin],[ThicknessMax],[IsDenseLine],[LineTraceUpNum],[LineTraceUpMax]," +
                        $"[LineTraceDownNum],[LineTraceDownMax],[LineTraceCount],[SumdgeUpExist],[SmudgeUpArea],[SumdgeUpNum],[SumdgeUpReverse],[HoleExistUp],[SumdgeUpHoleExist]," +
                        $"[SumdgeDownExist],[SumdgeDownArea],[SumdgeDownNum],[SumdgeDownReverse],[HoleExistDown],[SumdgeDownHoleExist],[SubfissureExist01],[SubfissureArea01],[SubfissureNum01]," +
                        $"[SubfissureBreakExist01],[SubfissureBreakArea01],[SubfissureBreakNum01],[SubfissureHoleExist01],[SubfissureHoleNum01],[SubfissureExist02],[SubfissureArea02],[SubfissureNum02]," +
                        $"[SubfissureBreakExist02],[SubfissureBreakArea02],[SubfissureBreakNum02],[SubfissureHoleExist02],[SubfissureHoleNum02] from {tableName} Where [{queryFields[0]}] = @{queryFields[0]}  Order By WaferId + 1  {direction};";
                    SqlParameter[] parameters = new SqlParameter[]
                    {
                        new SqlParameter($"@{queryFields[0]}",queryVals[0]),
                    };
                    table = DataAccess.GetDataTables(sql, parameters);
                }
                else if (queryFields.Count == 2 && queryVals.Count == 2)
                {
                    string sql = $"select  [DetectedTime] ,[ProductionDate],[WaferId],[CutNumber],[CrystalNumber],[PositionNumber]," +
                        $"[ProductionLot],[FlowerNumber],[DetectionRecipe],[DetectedLevel],[LevelType]      ,[TypeDescription]     ,[BoxNumber],[ThicknessAver],[TTV]     ,[LineTraceMax] ,[Warping]  ,[ResistivityAver] ," +
                        $"[ResistivityMax] ,[ResistivityMin] ,[LengthXMax],[LengthXMin],[LengthYMax],[LengthYMin] ,[LengthMax] ,[LengthMin] ,[LengthX],[LengthY],[DiagonalLeftStart],[DialonalRightStart]," +
                        $"[ChamferMax],[ChamferMin],[UpDownParallel]  ,[LeftRightParallel],[SquareLineMax] ,[SquareLineMin],[VerticalAngleMax],[VerticalAngleMin]      ,[LeftTopCharmfer]," +
                        $"[RightTopCharmfer],[LeftBottomCharmfer],[RightBottomCharmfer],[LeftTopAngle],[RightTopAngle],[LeftBottomAngle],[RightBottomAngle],[FrontEdgeBreakExist],[FrontEdgeBreakNum]," +
                        $"[FrontEdgeBreakArea],[BackEdgeBreakExist],[BackEdgeBreakNum],[BackEdgeBreakArea],[LeftEdgeBreakExist],[LeftEdgeBreakNum],[LeftSurfaceBreakExist],[LeftSurfaceBreakNum]," +
                        $"[RightEdgeBreakExist],[RightEdgeBreakNum],[RightSurfaceBreakExist],[RightSurfaceBreakNum],[ThicknessMin],[ThicknessMax],[IsDenseLine],[LineTraceUpNum],[LineTraceUpMax]," +
                        $"[LineTraceDownNum],[LineTraceDownMax],[LineTraceCount],[SumdgeUpExist],[SmudgeUpArea],[SumdgeUpNum],[SumdgeUpReverse],[HoleExistUp],[SumdgeUpHoleExist]," +
                        $"[SumdgeDownExist],[SumdgeDownArea],[SumdgeDownNum],[SumdgeDownReverse],[HoleExistDown],[SumdgeDownHoleExist],[SubfissureExist01],[SubfissureArea01],[SubfissureNum01]," +
                        $"[SubfissureBreakExist01],[SubfissureBreakArea01],[SubfissureBreakNum01],[SubfissureHoleExist01],[SubfissureHoleNum01],[SubfissureExist02],[SubfissureArea02],[SubfissureNum02]," +
                        $"[SubfissureBreakExist02],[SubfissureBreakArea02],[SubfissureBreakNum02],[SubfissureHoleExist02],[SubfissureHoleNum02] from from {tableName} Where [{queryFields[0]}] = @{queryFields[0]} And [{queryFields[1]}] = @{queryFields[1]} Order By WaferId + 1 {direction};";
                    SqlParameter[] parameters = new SqlParameter[]
                    {
                           new SqlParameter($"@{queryFields[0]}",queryVals[0]),
                           new SqlParameter($"@{queryFields[1]}",queryVals[1])
                    };
                    table = DataAccess.GetDataTables(sql, parameters);
                }
                else
                {
                    string sql = $"select  [DetectedTime] ,[ProductionDate],[WaferId],[CutNumber],[CrystalNumber],[PositionNumber]," +
                        $"[ProductionLot],[FlowerNumber],[DetectionRecipe],[DetectedLevel],[LevelType]      ,[TypeDescription]     ,[BoxNumber],[ThicknessAver],[TTV]     ,[LineTraceMax] ,[Warping]  ,[ResistivityAver] ," +
                        $"[ResistivityMax] ,[ResistivityMin] ,[LengthXMax],[LengthXMin],[LengthYMax],[LengthYMin] ,[LengthMax] ,[LengthMin] ,[LengthX],[LengthY],[DiagonalLeftStart],[DialonalRightStart]," +
                        $"[ChamferMax],[ChamferMin],[UpDownParallel]  ,[LeftRightParallel],[SquareLineMax] ,[SquareLineMin],[VerticalAngleMax],[VerticalAngleMin]      ,[LeftTopCharmfer]," +
                        $"[RightTopCharmfer],[LeftBottomCharmfer],[RightBottomCharmfer],[LeftTopAngle],[RightTopAngle],[LeftBottomAngle],[RightBottomAngle],[FrontEdgeBreakExist],[FrontEdgeBreakNum]," +
                        $"[FrontEdgeBreakArea],[BackEdgeBreakExist],[BackEdgeBreakNum],[BackEdgeBreakArea],[LeftEdgeBreakExist],[LeftEdgeBreakNum],[LeftSurfaceBreakExist],[LeftSurfaceBreakNum]," +
                        $"[RightEdgeBreakExist],[RightEdgeBreakNum],[RightSurfaceBreakExist],[RightSurfaceBreakNum],[ThicknessMin],[ThicknessMax],[IsDenseLine],[LineTraceUpNum],[LineTraceUpMax]," +
                        $"[LineTraceDownNum],[LineTraceDownMax],[LineTraceCount],[SumdgeUpExist],[SmudgeUpArea],[SumdgeUpNum],[SumdgeUpReverse],[HoleExistUp],[SumdgeUpHoleExist]," +
                        $"[SumdgeDownExist],[SumdgeDownArea],[SumdgeDownNum],[SumdgeDownReverse],[HoleExistDown],[SumdgeDownHoleExist],[SubfissureExist01],[SubfissureArea01],[SubfissureNum01]," +
                        $"[SubfissureBreakExist01],[SubfissureBreakArea01],[SubfissureBreakNum01],[SubfissureHoleExist01],[SubfissureHoleNum01],[SubfissureExist02],[SubfissureArea02],[SubfissureNum02]," +
                        $"[SubfissureBreakExist02],[SubfissureBreakArea02],[SubfissureBreakNum02],[SubfissureHoleExist02],[SubfissureHoleNum02] from {tableName} Order By {orderBy} {direction};";
                    table = DataAccess.GetDataTables(sql, null);
                }
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    result.State = true;
                    return result;
                }
                result.Data = table;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        public static DataResult<List<WaferDetectedDetailEntity>> GetResultSummaryByCondition(string crystalNumber, List<string> queryFields, List<string> queryVals, string orderBy = "Id", bool isDesc = false)
        {
            DataResult<List<WaferDetectedDetailEntity>> result = new DataResult<List<WaferDetectedDetailEntity>>();
            try
            {
                string tableName = TableManager.GetTableNameByCrystalNumber(crystalNumber);
                string direction = isDesc ? "Desc" : "Asc";
                DataTable table;
                if (queryFields.Count == 1 && queryVals.Count == 1)
                {
                    string sql = $"select  [DetectedTime] ,[ProductionDate],[WaferId],[CutNumber],[CrystalNumber],[PositionNumber]," +
                        $"[ProductionLot],[FlowerNumber],[DetectionRecipe],[DetectedLevel],[LevelType]      ,[TypeDescription]     ,[BoxNumber],[ThicknessAver],[TTV]     ,[LineTraceMax] ,[Warping]  ,[ResistivityAver] ," +
                        $"[ResistivityMax] ,[ResistivityMin] ,[LengthXMax],[LengthXMin],[LengthYMax],[LengthYMin] ,[LengthMax] ,[LengthMin] ,[LengthX],[LengthY],[DiagonalLeftStart],[DialonalRightStart]," +
                        $"[ChamferMax],[ChamferMin],[UpDownParallel]  ,[LeftRightParallel],[SquareLineMax] ,[SquareLineMin],[VerticalAngleMax],[VerticalAngleMin]      ,[LeftTopCharmfer]," +
                        $"[RightTopCharmfer],[LeftBottomCharmfer],[RightBottomCharmfer],[LeftTopAngle],[RightTopAngle],[LeftBottomAngle],[RightBottomAngle],[FrontEdgeBreakExist],[FrontEdgeBreakNum]," +
                        $"[FrontEdgeBreakArea],[BackEdgeBreakExist],[BackEdgeBreakNum],[BackEdgeBreakArea],[LeftEdgeBreakExist],[LeftEdgeBreakNum],[LeftSurfaceBreakExist],[LeftSurfaceBreakNum]," +
                        $"[RightEdgeBreakExist],[RightEdgeBreakNum],[RightSurfaceBreakExist],[RightSurfaceBreakNum],[ThicknessMin],[ThicknessMax],[IsDenseLine],[LineTraceUpNum],[LineTraceUpMax]," +
                        $"[LineTraceDownNum],[LineTraceDownMax],[LineTraceCount],[SumdgeUpExist],[SmudgeUpArea],[SumdgeUpNum],[SumdgeUpReverse],[HoleExistUp],[SumdgeUpHoleExist]," +
                        $"[SumdgeDownExist],[SumdgeDownArea],[SumdgeDownNum],[SumdgeDownReverse],[HoleExistDown],[SumdgeDownHoleExist],[SubfissureExist01],[SubfissureArea01],[SubfissureNum01]," +
                        $"[SubfissureBreakExist01],[SubfissureBreakArea01],[SubfissureBreakNum01],[SubfissureHoleExist01],[SubfissureHoleNum01],[SubfissureExist02],[SubfissureArea02],[SubfissureNum02]," +
                        $"[SubfissureBreakExist02],[SubfissureBreakArea02],[SubfissureBreakNum02],[SubfissureHoleExist02],[SubfissureHoleNum02] from {tableName} Where [{queryFields[0]}] = @{queryFields}  Order By {orderBy} {direction};";
                    SqlParameter[] parameters = new SqlParameter[]
                    {
                        new SqlParameter($"@{queryFields[0]}",queryVals[0]),
                    };
                    table = DataAccess.GetDataTables(sql, parameters);
                }
                else if (queryFields.Count == 2 && queryVals.Count == 2)
                {
                    string sql = $"select  * from {tableName} Where [{queryFields[0]}] = @{queryFields} And [{queryFields[1]}] = @{queryFields[1]} Order By WaferId + 1  {direction};";
                    SqlParameter[] parameters = new SqlParameter[]
                    {
                           new SqlParameter($"@{queryFields[0]}",queryVals[0]),
                           new SqlParameter($"@{queryFields[1]}",queryVals[1])
                    };
                    table = DataAccess.GetDataTables(sql, parameters);
                }
                else
                {
                    string sql = $"select  * from {tableName} Order By {orderBy} {direction};";
                    table = DataAccess.GetDataTables(sql, null);
                }
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    result.State = true;
                    return result;
                }
                List<WaferDetectedDetailEntity> dataList = (from q in table.AsEnumerable()
                                                            select new WaferDetectedDetailEntity
                                                            {
                                                                DetectedTime = q.Field<string>("DetectedTime"),
                                                                ProductionDate = q.Field<string>("ProductionDate"),
                                                                WaferId = q.Field<string>("WaferId"),
                                                                CutNumber = q.Field<string>("CutNumber"),
                                                                CrystalNumber = q.Field<string>("CrystalNumber"),
                                                                PositionNumber = q.Field<string>("PositionNumber"),
                                                                ProductionLot = q.Field<string>("ProductionLot"),
                                                                FlowerNumber = q.Field<string>("FlowerNumber"),
                                                                DetectionRecipe = q.Field<string>("DetectionRecipe"),
                                                                DetectedLevel = q.Field<string>("DetectedLevel"),
                                                                LevelType = q.Field<string>("LevelType"),
                                                                TypeDescription = q.Field<string>("TypeDescription"),
                                                                BoxNumber = q.Field<string>("BoxNumber"),
                                                                ThicknessAver = q.Field<string>("ThicknessAver"),
                                                                TTV = q.Field<string>("TTV"),
                                                                LineTraceMax = q.Field<string>("LineTraceMax"),
                                                                Warping = q.Field<string>("Warping"),
                                                                ThicknessMin = q.Field<string>("ThicknessMin"),
                                                                ThicknessMax = q.Field<string>("ThicknessMax"),
                                                                IsDenseLine = q.Field<string>("IsDenseLine"),
                                                                LineTraceUpNum = q.Field<string>("LineTraceUpNum"),
                                                                LineTraceUpMax = q.Field<string>("LineTraceUpMax"),
                                                                LineTraceDownNum = q.Field<string>("LineTraceDownNum"),
                                                                LineTraceDownMax = q.Field<string>("LineTraceDownMax"),
                                                                LineTraceCount = q.Field<string>("LineTraceCount"),
                                                                ResistivityAver = q.Field<string>("ResistivityAver"),
                                                                ResistivityMax = q.Field<string>("ResistivityMax"),
                                                                ResistivityMin = q.Field<string>("ResistivityMin"),
                                                                LengthMax = q.Field<string>("LengthMax"),
                                                                LengthMin = q.Field<string>("LengthMin"),
                                                                LengthX = q.Field<string>("LengthX"),
                                                                LengthY = q.Field<string>("LengthY"),
                                                                DiagonalLeftStart = q.Field<string>("DiagonalLeftStart"),
                                                                DialonalRightStart = q.Field<string>("DialonalRightStart"),
                                                                ChamferMax = q.Field<string>("ChamferMax"),
                                                                ChamferMin = q.Field<string>("ChamferMin"),
                                                                UpDownParallel = q.Field<string>("UpDownParallel"),
                                                                LeftRightParallel = q.Field<string>("LeftRightParallel"),
                                                                SquareLineMax = q.Field<string>("SquareLineMax"),
                                                                SquareLineMin = q.Field<string>("SquareLineMin"),
                                                                VerticalAngleMax = q.Field<string>("VerticalAngleMax"),
                                                                VerticalAngleMin = q.Field<string>("VerticalAngleMin"),
                                                                LeftTopCharmfer = q.Field<string>("LeftTopCharmfer"),
                                                                RightTopCharmfer = q.Field<string>("RightTopCharmfer"),
                                                                LeftBottomCharmfer = q.Field<string>("LeftBottomCharmfer"),
                                                                RightBottomCharmfer = q.Field<string>("RightBottomCharmfer"),
                                                                LeftTopAngle = q.Field<string>("LeftTopAngle"),
                                                                RightTopAngle = q.Field<string>("RightTopAngle"),
                                                                LeftBottomAngle = q.Field<string>("LeftBottomAngle"),
                                                                RightBottomAngle = q.Field<string>("RightBottomAngle"),
                                                                LengthXMax = q.Field<string>("LengthXMax"),
                                                                LengthXMin = q.Field<string>("LengthXMin"),
                                                                LengthYMax = q.Field<string>("LengthYMax"),
                                                                LengthYMin = q.Field<string>("LengthYMin"),
                                                                FrontEdgeBreakExist = q.Field<string>("FrontEdgeBreakExist"),
                                                                FrontEdgeBreakNum = q.Field<string>("FrontEdgeBreakNum"),
                                                                FrontEdgeBreakArea = q.Field<string>("FrontEdgeBreakArea"),
                                                                BackEdgeBreakExist = q.Field<string>("BackEdgeBreakExist"),
                                                                BackEdgeBreakNum = q.Field<string>("BackEdgeBreakNum"),
                                                                BackEdgeBreakArea = q.Field<string>("BackEdgeBreakArea"),
                                                                LeftEdgeBreakExist = q.Field<string>("LeftEdgeBreakExist"),
                                                                LeftEdgeBreakNum = q.Field<string>("LeftEdgeBreakNum"),
                                                                LeftSurfaceBreakExist = q.Field<string>("LeftSurfaceBreakExist"),
                                                                LeftSurfaceBreakNum = q.Field<string>("LeftSurfaceBreakNum"),
                                                                RightEdgeBreakExist = q.Field<string>("RightEdgeBreakExist"),
                                                                RightEdgeBreakNum = q.Field<string>("RightEdgeBreakNum"),
                                                                RightSurfaceBreakExist = q.Field<string>("RightSurfaceBreakExist"),
                                                                RightSurfaceBreakNum = q.Field<string>("RightSurfaceBreakNum"),
                                                                SumdgeUpExist = q.Field<string>("SumdgeUpExist"),
                                                                SmudgeUpArea = q.Field<string>("SmudgeUpArea"),
                                                                SumdgeUpNum = q.Field<string>("SumdgeUpNum"),
                                                                SumdgeUpReverse = q.Field<string>("SumdgeUpReverse"),
                                                                SumdgeUpHoleExist = q.Field<string>("SumdgeUpHoleExist"),
                                                                SumdgeUpHoleNum = q.Field<string>("SumdgeUpHoleNum"),
                                                                HoleExistUp = q.Field<string>("HoleExistUp"),
                                                                HoleNumUp = q.Field<string>("HoleNumUp"),
                                                                SumdgeDownExist = q.Field<string>("SumdgeDownExist"),
                                                                SumdgeDownArea = q.Field<string>("SumdgeDownArea"),
                                                                SumdgeDownNum = q.Field<string>("SumdgeDownNum"),
                                                                SumdgeDownReverse = q.Field<string>("SumdgeDownReverse"),
                                                                SumdgeDownHoleExist = q.Field<string>("SumdgeDownHoleExist"),
                                                                SumdgeDownHoleNum = q.Field<string>("SumdgeDownHoleNum"),
                                                                HoleExistDown = q.Field<string>("HoleExistDown"),
                                                                HoleNumDown = q.Field<string>("HoleNumDown"),
                                                                SubfissureArea01 = q.Field<string>("SubfissureArea01"),
                                                                SubfissureNum01 = q.Field<string>("SubfissureNum01"),
                                                                SubfissureExist01 = q.Field<string>("SubfissureExist01"),
                                                                SubfissureBreakArea01 = q.Field<string>("SubfissureBreakArea01"),
                                                                SubfissureBreakNum01 = q.Field<string>("SubfissureBreakNum01"),
                                                                SubfissureBreakExist01 = q.Field<string>("SubfissureBreakExist01"),
                                                                SubfissureHoleNum01 = q.Field<string>("SubfissureHoleNum01"),
                                                                SubfissureHoleExist01 = q.Field<string>("SubfissureHoleExist01"),
                                                                SubfissureArea02 = q.Field<string>("SubfissureArea02"),
                                                                SubfissureNum02 = q.Field<string>("SubfissureNum02"),
                                                                SubfissureExist02 = q.Field<string>("SubfissureExist02"),
                                                                SubfissureBreakArea02 = q.Field<string>("SubfissureBreakArea02"),
                                                                SubfissureBreakNum02 = q.Field<string>("SubfissureBreakNum02"),
                                                                SubfissureBreakExist02 = q.Field<string>("SubfissureBreakExist02"),
                                                                SubfissureHoleNum02 = q.Field<string>("SubfissureHoleNum02"),
                                                                SubfissureHoleExist02 = q.Field<string>("SubfissureHoleExist02"),
                                                            }).ToList();
                result.Data = dataList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取检测结果汇总,所有的数据.
        /// </summary>
        /// <returns></returns>
        public static DataResult<List<WaferDetectedDetailEntity>> GetResultSummary(string crystalNumber, string orderBy = "Id", bool isDesc = false, int dataCount = -1)
        {
            DataResult<List<WaferDetectedDetailEntity>> result = new DataResult<List<WaferDetectedDetailEntity>>();
            try
            {
                string tableName = TableManager.GetTableNameByCrystalNumber(crystalNumber);
                string direction = isDesc ? "Desc" : "Asc";
                string sql = $"select Top {dataCount} * from {tableName} Order By {orderBy} {direction};";
                if (dataCount == -1)
                {
                    sql = $"select * from {tableName} Order By WaferId + 1 {direction};";
                }
                DataTable table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count == 0)
                {
                    result.Message = $"数据表里面无数据";
                    result.State = true;
                    return result;
                }
                List<WaferDetectedDetailEntity> moduleShieldStateList = (from q in table.AsEnumerable()
                                                                         select new WaferDetectedDetailEntity
                                                                         {
                                                                             DetectedTime = q.Field<string>("DetectedTime"),
                                                                             ProductionDate = q.Field<string>("ProductionDate"),
                                                                             WaferId = q.Field<string>("WaferId"),
                                                                             CutNumber = q.Field<string>("CutNumber"),
                                                                             CrystalNumber = q.Field<string>("CrystalNumber"),
                                                                             PositionNumber = q.Field<string>("PositionNumber"),
                                                                             ProductionLot = q.Field<string>("ProductionLot"),
                                                                             FlowerNumber = q.Field<string>("FlowerNumber"),
                                                                             DetectionRecipe = q.Field<string>("DetectionRecipe"),
                                                                             DetectedLevel = q.Field<string>("DetectedLevel"),
                                                                             LevelType = q.Field<string>("LevelType"),
                                                                             TypeDescription = q.Field<string>("TypeDescription"),
                                                                             BoxNumber = q.Field<string>("BoxNumber"),
                                                                             ThicknessAver = q.Field<string>("ThicknessAver"),
                                                                             TTV = q.Field<string>("TTV"),
                                                                             LineTraceMax = q.Field<string>("LineTraceMax"),
                                                                             Warping = q.Field<string>("Warping"),
                                                                             ThicknessMin = q.Field<string>("ThicknessMin"),
                                                                             ThicknessMax = q.Field<string>("ThicknessMax"),
                                                                             IsDenseLine = q.Field<string>("IsDenseLine"),
                                                                             LineTraceUpNum = q.Field<string>("LineTraceUpNum"),
                                                                             LineTraceUpMax = q.Field<string>("LineTraceUpMax"),
                                                                             LineTraceDownNum = q.Field<string>("LineTraceDownNum"),
                                                                             LineTraceDownMax = q.Field<string>("LineTraceDownMax"),
                                                                             LineTraceCount = q.Field<string>("LineTraceCount"),
                                                                             ResistivityAver = q.Field<string>("ResistivityAver"),
                                                                             ResistivityMax = q.Field<string>("ResistivityMax"),
                                                                             ResistivityMin = q.Field<string>("ResistivityMin"),
                                                                             LengthMax = q.Field<string>("LengthMax"),
                                                                             LengthMin = q.Field<string>("LengthMin"),
                                                                             LengthX = q.Field<string>("LengthX"),
                                                                             LengthY = q.Field<string>("LengthY"),
                                                                             DiagonalLeftStart = q.Field<string>("DiagonalLeftStart"),
                                                                             DialonalRightStart = q.Field<string>("DialonalRightStart"),
                                                                             ChamferMax = q.Field<string>("ChamferMax"),
                                                                             ChamferMin = q.Field<string>("ChamferMin"),
                                                                             UpDownParallel = q.Field<string>("UpDownParallel"),
                                                                             LeftRightParallel = q.Field<string>("LeftRightParallel"),
                                                                             SquareLineMax = q.Field<string>("SquareLineMax"),
                                                                             SquareLineMin = q.Field<string>("SquareLineMin"),
                                                                             VerticalAngleMax = q.Field<string>("VerticalAngleMax"),
                                                                             VerticalAngleMin = q.Field<string>("VerticalAngleMin"),
                                                                             LeftTopCharmfer = q.Field<string>("LeftTopCharmfer"),
                                                                             RightTopCharmfer = q.Field<string>("RightTopCharmfer"),
                                                                             LeftBottomCharmfer = q.Field<string>("LeftBottomCharmfer"),
                                                                             RightBottomCharmfer = q.Field<string>("RightBottomCharmfer"),
                                                                             LeftTopAngle = q.Field<string>("LeftTopAngle"),
                                                                             RightTopAngle = q.Field<string>("RightTopAngle"),
                                                                             LeftBottomAngle = q.Field<string>("LeftBottomAngle"),
                                                                             RightBottomAngle = q.Field<string>("RightBottomAngle"),
                                                                             LengthXMax = q.Field<string>("LengthXMax"),
                                                                             LengthXMin = q.Field<string>("LengthXMin"),
                                                                             LengthYMax = q.Field<string>("LengthYMax"),
                                                                             LengthYMin = q.Field<string>("LengthYMin"),
                                                                             FrontEdgeBreakExist = q.Field<string>("FrontEdgeBreakExist"),
                                                                             FrontEdgeBreakNum = q.Field<string>("FrontEdgeBreakNum"),
                                                                             FrontEdgeBreakArea = q.Field<string>("FrontEdgeBreakArea"),
                                                                             BackEdgeBreakExist = q.Field<string>("BackEdgeBreakExist"),
                                                                             BackEdgeBreakNum = q.Field<string>("BackEdgeBreakNum"),
                                                                             BackEdgeBreakArea = q.Field<string>("BackEdgeBreakArea"),
                                                                             LeftEdgeBreakExist = q.Field<string>("LeftEdgeBreakExist"),
                                                                             LeftEdgeBreakNum = q.Field<string>("LeftEdgeBreakNum"),
                                                                             LeftSurfaceBreakExist = q.Field<string>("LeftSurfaceBreakExist"),
                                                                             LeftSurfaceBreakNum = q.Field<string>("LeftSurfaceBreakNum"),
                                                                             RightEdgeBreakExist = q.Field<string>("RightEdgeBreakExist"),
                                                                             RightEdgeBreakNum = q.Field<string>("RightEdgeBreakNum"),
                                                                             RightSurfaceBreakExist = q.Field<string>("RightSurfaceBreakExist"),
                                                                             RightSurfaceBreakNum = q.Field<string>("RightSurfaceBreakNum"),
                                                                             SumdgeUpExist = q.Field<string>("SumdgeUpExist"),
                                                                             SmudgeUpArea = q.Field<string>("SmudgeUpArea"),
                                                                             SumdgeUpNum = q.Field<string>("SumdgeUpNum"),
                                                                             SumdgeUpReverse = q.Field<string>("SumdgeUpReverse"),
                                                                             SumdgeUpHoleExist = q.Field<string>("SumdgeUpHoleExist"),
                                                                             SumdgeUpHoleNum = q.Field<string>("SumdgeUpHoleNum"),
                                                                             HoleExistUp = q.Field<string>("HoleExistUp"),
                                                                             HoleNumUp = q.Field<string>("HoleNumUp"),
                                                                             SumdgeDownExist = q.Field<string>("SumdgeDownExist"),
                                                                             SumdgeDownArea = q.Field<string>("SumdgeDownArea"),
                                                                             SumdgeDownNum = q.Field<string>("SumdgeDownNum"),
                                                                             SumdgeDownReverse = q.Field<string>("SumdgeDownReverse"),
                                                                             SumdgeDownHoleExist = q.Field<string>("SumdgeDownHoleExist"),
                                                                             SumdgeDownHoleNum = q.Field<string>("SumdgeDownHoleNum"),
                                                                             HoleExistDown = q.Field<string>("HoleExistDown"),
                                                                             HoleNumDown = q.Field<string>("HoleNumDown"),
                                                                             SubfissureArea01 = q.Field<string>("SubfissureArea01"),
                                                                             SubfissureNum01 = q.Field<string>("SubfissureNum01"),
                                                                             SubfissureExist01 = q.Field<string>("SubfissureExist01"),
                                                                             SubfissureBreakArea01 = q.Field<string>("SubfissureBreakArea01"),
                                                                             SubfissureBreakNum01 = q.Field<string>("SubfissureBreakNum01"),
                                                                             SubfissureBreakExist01 = q.Field<string>("SubfissureBreakExist01"),
                                                                             SubfissureHoleNum01 = q.Field<string>("SubfissureHoleNum01"),
                                                                             SubfissureHoleExist01 = q.Field<string>("SubfissureHoleExist01"),
                                                                             SubfissureArea02 = q.Field<string>("SubfissureArea02"),
                                                                             SubfissureNum02 = q.Field<string>("SubfissureNum02"),
                                                                             SubfissureExist02 = q.Field<string>("SubfissureExist02"),
                                                                             SubfissureBreakArea02 = q.Field<string>("SubfissureBreakArea02"),
                                                                             SubfissureBreakNum02 = q.Field<string>("SubfissureBreakNum02"),
                                                                             SubfissureBreakExist02 = q.Field<string>("SubfissureBreakExist02"),
                                                                             SubfissureHoleNum02 = q.Field<string>("SubfissureHoleNum02"),
                                                                             SubfissureHoleExist02 = q.Field<string>("SubfissureHoleExist02"),
                                                                         }).ToList();
                result.Data = moduleShieldStateList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        public static DataResult<List<CrystalResultEntity>> GetCrystalResult(string orderBy = "Id", bool isDesc = false, string queryField = "", string queryVal = "")
        {
            DataResult<List<CrystalResultEntity>> result = new DataResult<List<CrystalResultEntity>>();
            try
            {
                string tableName = TableNames.CrystalRecordTb;
                string direction = isDesc ? "Desc" : "Asc";
                string sql = "";
                SqlParameter[]? parameters;
                if (!string.IsNullOrEmpty(queryField) && !string.IsNullOrEmpty(queryVal))
                {
                    parameters = new SqlParameter[]
                    {
                        new SqlParameter($"@{queryField}",SqlDbType.VarChar){Value = queryVal}
                    };
                    sql = $"select  * from {tableName} Where {queryField} = @{queryField} Order By {orderBy} {direction};";
                }
                else
                {
                    parameters = null;
                    sql = $"select  * from {tableName} Order By {orderBy} {direction};";
                }

                DataTable table = DataAccess.GetDataTables(sql, parameters);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是里面无数据";
                    return result;
                }
                List<CrystalResultEntity> crystalResultList = (from q in table.AsEnumerable()
                                                               select new CrystalResultEntity
                                                               {
                                                                   Id = q.Field<int>("Id"),
                                                                   CrystalNumber = q.Field<string>("CrystalNumber"),
                                                                   ProductionDate = q.Field<string>("ProductionDate"),
                                                                   Lv01 = q.Field<string>("Lv01"),
                                                                   Lv02 = q.Field<string>("Lv02"),
                                                                   Lv03 = q.Field<string>("Lv03"),
                                                                   Lv04 = q.Field<string>("Lv04"),
                                                                   Lv05 = q.Field<string>("Lv05"),
                                                                   Lv06 = q.Field<string>("Lv06"),
                                                                   Lv07 = q.Field<string>("Lv07"),
                                                                   Lv08 = q.Field<string>("Lv08"),
                                                                   Lv09 = q.Field<string>("Lv09"),
                                                                   Lv10 = q.Field<string>("Lv10"),
                                                                   Lv11 = q.Field<string>("Lv11"),
                                                                   Lv12 = q.Field<string>("Lv12"),
                                                                   Lv13 = q.Field<string>("Lv13"),
                                                                   Lv14 = q.Field<string>("Lv14"),
                                                                   Lv15 = q.Field<string>("Lv15"),
                                                                   Lv16 = q.Field<string>("Lv16"),
                                                                   Lv17 = q.Field<string>("Lv17"),
                                                                   Lv18 = q.Field<string>("Lv18"),
                                                                   Lv19 = q.Field<string>("Lv19"),
                                                                   Lv20 = q.Field<string>("Lv20"),
                                                                   Lv21 = q.Field<string>("Lv21"),
                                                                   Lv22 = q.Field<string>("Lv22"),
                                                                   Lv23 = q.Field<string>("Lv23"),
                                                                   Lv24 = q.Field<string>("Lv24"),
                                                                   Lv25 = q.Field<string>("Lv25"),
                                                                   Lv26 = q.Field<string>("Lv26"),
                                                               }).ToList();
                result.Data = crystalResultList;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        #endregion


        #region 2. 更新数据

        /// <summary>
        /// 更新模块屏蔽状态.
        /// </summary>
        /// <param name="queryName"></param>
        /// <param name="newVal"></param>
        /// <returns></returns>
        public static DataResult UpdateModuleShieldedStateTb(string queryName, bool newVal)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.ModuleShieldStateTb;
            try
            {
                string sql = $"UPDATE [dbo].[{tableName}] SET [IsShielded] = @IsShielded WHERE [ModuleName] = @ModuleName";
                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@IsShielded",SqlDbType.Bit){Value = newVal},
                    new SqlParameter("@ModuleName",SqlDbType.VarChar){Value = queryName}
                };
                var count = SqlHelper.ExecuteNonQuery(sql, parameters);
                if (count > 0)
                {
                    result.State = true;
                    result.Message = $"表{tableName} 更新成功,更新内容 {queryName}的屏蔽状态 = {newVal}";
                }
                else
                {
                    result.Message = $"数据库{tableName} 更新失败!";
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="queryField">查询的字段名称</param>
        /// <param name="queryVal">查询的字段的值</param>
        /// <param name="newVal">更新成新的值</param>
        /// <returns></returns>
        public static DataResult UpdateBoxesStateTb(string queryField, string queryVal, string updateField, string updateVal)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.BoxesStateTb;
            try
            {
                string sql = $"UPDATE [dbo].[{tableName}] SET [{updateField}] = @{updateField} WHERE [{queryField}] = @{queryField}";
                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter($"@{updateField}",SqlDbType.VarChar){Value = updateVal},
                    new SqlParameter($"@{queryField}",SqlDbType.VarChar){Value = queryVal}
                };
                var count = SqlHelper.ExecuteNonQuery(sql, parameters);
                if (count > 0)
                {
                    result.State = true;
                    result.Message = $"表{tableName} 更新成功,更新内容 {updateField} = {updateVal}";
                }
                else
                {
                    result.Message = $"数据库{tableName} 更新失败!";
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        /// <summary>
        /// 更新当前作业信息的数据库内容
        /// </summary>
        /// <param name="updateFields"></param>
        /// <param name="updateValues"></param>
        /// <returns></returns>
        public static DataResult UpdateWorkingInfo(List<string> updateFields, List<string> updateVals)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.WorkingInfoTb;
            int queryId = 1; // 只有一条数据,默认的WorkingId为1
            try
            {
                string sql = $"UPDATE [dbo].[{tableName}] SET";
                foreach (var field in updateFields)
                {
                    sql += $" [{field}] = @{field},";
                }
                sql = sql.RemoveLast(1); // 移除掉最后的那个逗号
                sql += $" Where[WorkingId]=@WorkingId";

                List<SqlParameter> updateParameters = new List<SqlParameter>()
                {
                    new SqlParameter($"@WorkingId",queryId)
                };
                for (int i = 0; i < updateFields.Count(); i++)
                {
                    updateParameters.Add(new SqlParameter($"@{updateFields[i]}", SqlDbType.VarChar) { Value = updateVals[i] });
                }
                int count = SqlHelper.ExecuteNonQuery(sql, updateParameters.ToArray());
                if (count <= 0)
                {
                    result.Message = $"数据更新失败,请检查表{tableName}中WorkingId = {queryId} 的数据是否存在";
                    return result;
                }
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 更新视觉补偿的值.
        /// </summary>
        /// <param name="queryField"></param>
        /// <param name="queryVal"></param>
        /// <param name="updateFields"></param>
        /// <param name="updateVals"></param>
        /// <returns></returns>
        public static DataResult UpdateVisionOffset(string queryField, string queryVal, List<string> updateFields, List<double> updateVals)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.VisionOffsetTb;

            try
            {
                string sql = $"UPDATE [dbo].[{tableName}] SET";
                foreach (var field in updateFields)
                {
                    sql += $" [{field}] = @{field},";
                }
                sql = sql.RemoveLast(1); // 移除掉最后的那个逗号
                sql += $" Where[{queryField}]=@{queryField} ;";

                List<SqlParameter> updateParameters = new List<SqlParameter>()
                {
                    new SqlParameter($"@{queryField}",SqlDbType.VarChar){Value = queryVal},
                };
                for (int i = 0; i < updateFields.Count(); i++)
                {
                    updateParameters.Add(new SqlParameter($"@{updateFields[i]}", SqlDbType.VarChar) { Value = updateVals[i] });
                }
                int count = SqlHelper.ExecuteNonQuery(sql, updateParameters.ToArray());
                if (count > 0)
                {
                    result.State = true;
                    result.Message = $"表{tableName} 更新成功!";
                }
                else
                {
                    result.Message = $"表{tableName} 更新失败";
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        private static readonly object obj = new object();
        public static DataResult UpdateWaferDetectedDetailTb(List<string> queryFields, List<string> queryVals, List<string> updateFields, List<string> updateVals, string crystalNumber = "")
        {
            DataResult result = new DataResult();
            string tableName;
            if (crystalNumber == "")
            {
                tableName = TableManager.GetTableNameByCrystalNumber(GlobalValues.CrystalNumberCurrent!);
            }
            else
            {
                tableName = TableManager.GetTableNameByCrystalNumber(crystalNumber);
            }
            try
            {
                lock (obj)
                {
                    // 将日期更新
                    string sql = $"Select * From {tableName} Where [{queryFields[0]}]=@{queryFields[0]} And [{queryFields[1]}]=@{queryFields[1]};";
                    SqlParameter[] parameters = new SqlParameter[]
                     {
                        new SqlParameter($"@{queryFields[0]}",SqlDbType.VarChar){Value = queryVals[0]},
                        new SqlParameter($"@{queryFields[1]}",SqlDbType.VarChar){Value = queryVals[1]}
                     };
                    int count = SqlHelper.ExcuteGetCount(sql, parameters);
                    if (count <= 0)
                    {
                        SqlParameter[] insertParameters = new SqlParameter[]
                        {
                            new SqlParameter($"@{queryFields[0]}",SqlDbType.VarChar){Value = queryVals[0]},
                            new SqlParameter($"@{queryFields[1]}",SqlDbType.VarChar){Value = queryVals[1]},
                            new SqlParameter($"@{queryFields[2]}",SqlDbType.VarChar){Value = queryVals[2]},

                        };
                        sql = $"INSERT INTO {tableName} ({queryFields[0]},{queryFields[1]},{queryFields[2]}) " +
                                           $"VALUES (@{queryFields[0]}, @{queryFields[1]},@{queryFields[2]});";
                        count = SqlHelper.ExecuteNonQuery(sql, insertParameters);
                        if (count <= 0)
                        {
                            result.Message = $"{sql} 语句执行失败,数据插入失败";
                        }
                    }
                    // 执行成功,就开始执行插入的操作.
                    sql = $"UPDATE [dbo].[{tableName}] SET";
                    foreach (var field in updateFields)
                    {
                        sql += $" [{field}] = @{field},";
                    }
                    sql = sql.RemoveLast(1); // 移除掉最后的那个逗号
                    sql += $" Where[{queryFields[0]}]=@{queryFields[0]} And [{queryFields[1]}]=@{queryFields[1]};";

                    List<SqlParameter> updateParameters = new List<SqlParameter>()
                    {
                        new SqlParameter($"@{queryFields[0]}",SqlDbType.VarChar){Value = queryVals[0]},
                        new SqlParameter($"@{queryFields[1]}",SqlDbType.VarChar){Value = queryVals[1]}
                    };
                    for (int i = 0; i < updateFields.Count(); i++)
                    {
                        updateParameters.Add(new SqlParameter($"@{updateFields[i]}", SqlDbType.VarChar) { Value = updateVals[i] });
                    }
                    count = SqlHelper.ExecuteNonQuery(sql, updateParameters.ToArray());
                    if (count > 0)
                    {
                        result.State = true;
                        result.Message = $"表{tableName} 更新成功!";
                    }
                    else
                    {
                        result.Message = $"数据库{tableName} 更新失败!";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        private static readonly object obj02 = new object();

        /// <summary>
        /// PC正常分选统计的直流,可能是各种原因导致的. 这里还要分是因为等级导致的还是因为其他原因导致的.
        /// 如果是因为等级导致的,比如15等级以上,这个时候要保存对应等级的数值. 如果是15等级一下导致的,就不用保存了.
        /// </summary>
        /// <param name="crystalNumber"></param>
        /// <param name="directionNumber"></param>
        /// <returns></returns>
        internal static DataResult UpdateCrystalLevelCountDirection(string crystalNumber, int levelIndex)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.CrystalLevelCountTb;
            try
            {
                lock (obj02)
                {
                    string sqlQuery = $"Select [Count] From {tableName} Where [CrystalNumber] = @CrystalNumber And [LevelIndex] = @LevelIndex";
                    SqlParameter[] queryParameters = new SqlParameter[]
                    {
                        new SqlParameter($"@CrystalNumber",crystalNumber),
                        new SqlParameter($"@LevelIndex",levelIndex)
                    };
                    DataTable table;
                    string sqlUpdate = $"UPDATE [dbo].[{tableName}] SET [Count] = @Count Where [CrystalNumber] = @CrystalNumber And [LevelIndex] = @LevelIndex ;";
                    SqlParameter[] updateParameters;
                    // 如果不等于32,就更新对应的数据,比如3D数据错乱之类的错误.
                    if (levelIndex != 32)
                    {
                        table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                        if (table.Rows.Count <= 0)
                        {
                            result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                        }
                        else
                        {
                            // 将查询的数据拿到,然后去更新成新的值
                            string sqlCount = table.Rows[0].Field<string>("Count")!;
                            int newCount;
                            bool success = int.TryParse(sqlCount, out int number);
                            if (success)
                            {
                                // 如果是直流,就要直接使用PLC给出的统计的值.
                                newCount = number + 1;
                            }
                            else
                            {
                                newCount = 1;
                            }

                            // 更新本等级的数量
                            updateParameters = new SqlParameter[]
                            {
                                new SqlParameter("@Count",newCount),
                                new SqlParameter("@CrystalNumber",crystalNumber),
                                new SqlParameter("@LevelIndex",levelIndex)
                            };
                            int count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                            if (count <= 0)
                            {
                                result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                                return result;
                            }
                        }
                    }
                    // 更新直流数量.
                    queryParameters = new SqlParameter[]
                   {
                        new SqlParameter($"@CrystalNumber",crystalNumber),
                        new SqlParameter($"@LevelIndex",32)
                   };

                    table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                    if (table.Rows.Count <= 0)
                    {
                        result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                    }
                    else
                    {
                        // 将查询的数据拿到,然后去更新成新的值
                        string sqlCount = table.Rows[0].Field<string>("Count")!;
                        bool success = int.TryParse(sqlCount, out int number03);
                        int newCount;
                        if (success)
                        {
                            // 如果是直流,就要直接使用PLC给出的统计的值.
                            newCount = (number03 + 1);
                        }
                        else
                        {
                            newCount = 1;
                        }

                        updateParameters = new SqlParameter[]
                        {
                                new SqlParameter("@Count",newCount),
                                new SqlParameter("@CrystalNumber",crystalNumber),
                                new SqlParameter("@LevelIndex",32)
                        };

                        // 更新正常分选的值.
                        int count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                        if (count <= 0)
                        {
                            result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                            return result;
                        }
                    }


                    // 总数汇总
                    queryParameters = new SqlParameter[]
                    {
                        new SqlParameter($"@CrystalNumber",crystalNumber),
                        new SqlParameter($"@LevelIndex",38)
                    };

                    table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                    if (table.Rows.Count <= 0)
                    {
                        result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                    }
                    else
                    {
                        // 将查询的数据拿到,然后去更新成新的值
                        string sqlCount = table.Rows[0].Field<string>("Count")!;
                        bool success = int.TryParse(sqlCount, out int number03);
                        int newCount;
                        if (success)
                        {
                            // 总数+1
                            newCount = (number03 + 1);
                        }
                        else
                        {
                            newCount = 1;
                        }

                        updateParameters = new SqlParameter[]
                        {
                                new SqlParameter("@Count",newCount),
                                new SqlParameter("@CrystalNumber",crystalNumber),
                                new SqlParameter("@LevelIndex",38)
                        };

                        // 更新正常分选的值.
                        int count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                        if (count <= 0)
                        {
                            result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                            return result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }



        /// <summary>
        /// 更新异常数据,缺数直流数据更新.
        /// </summary>
        /// <param name="crystalNumber"></param>
        /// <param name="levelIndex"></param>
        /// <returns></returns>
        internal static DataResult UpdateCrystalLevelCountTbLoss(string crystalNumber, int levelIndex)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.CrystalLevelCountTb;
            try
            {
                lock (obj02)
                {

                    // 1. 先去查询这条数据是否存在,正常分选,非缺数直流,非直流,就是正常统计值.这里更新的时候,每次累加正常分选汇总即可.
                    // 2. 正常分选汇总 + 直流 + 缺数直流 = 总的汇总.
                    string sqlQuery = $"Select [Count] From {tableName} Where [CrystalNumber] = @CrystalNumber And [LevelIndex] = @LevelIndex";
                    SqlParameter[] queryParameters = new SqlParameter[]
                    {
                        new SqlParameter($"@CrystalNumber",crystalNumber),
                        new SqlParameter($"@LevelIndex",levelIndex)
                    };
                    DataTable table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                    if (table.Rows.Count <= 0)
                    {
                        result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                    }
                    else
                    {
                        // 将查询的数据拿到,然后去更新成新的值
                        string sqlCount = table.Rows[0].Field<string>("Count")!;
                        int newCount;
                        bool success = int.TryParse(sqlCount, out int number);
                        if (success)
                        {
                            // 如果是直流,就要直接使用PLC给出的统计的值.
                            newCount = (number + 1);
                        }
                        else
                        {
                            newCount = 1;
                        }

                        // 去更新数据,本次等级的值.
                        string sqlUpdate = $"UPDATE [dbo].[{tableName}] SET [Count] = @Count Where [CrystalNumber] = @CrystalNumber And [LevelIndex] = @LevelIndex ;";
                        SqlParameter[] updateParameters = new SqlParameter[]
                        {
                            new SqlParameter("@Count",newCount),
                            new SqlParameter("@CrystalNumber",crystalNumber),
                            new SqlParameter("@LevelIndex",levelIndex)
                        };
                        int count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                        if (count <= 0)
                        {
                            result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                            return result;
                        }

                        // 汇总数据+1
                        queryParameters = new SqlParameter[]
                        {
                            new SqlParameter($"@CrystalNumber",crystalNumber),
                            new SqlParameter($"@LevelIndex",38)
                        };

                        table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                        if (table.Rows.Count <= 0)
                        {
                            result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                        }
                        else
                        {
                            // 将查询的数据拿到,然后去更新成新的值
                            sqlCount = table.Rows[0].Field<string>("Count")!;
                            success = int.TryParse(sqlCount, out int number03);
                            if (success)
                            {
                                // 如果是直流,就要直接使用PLC给出的统计的值.
                                newCount = (number03 + 1);
                            }
                            else
                            {
                                newCount = 1;
                            }

                            updateParameters = new SqlParameter[]
                            {

                                    new SqlParameter("@Count",newCount),
                                    new SqlParameter("@CrystalNumber",crystalNumber),
                                    new SqlParameter("@LevelIndex",38)
                            };

                            // 更新正常分选的值.
                            count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                            if (count <= 0)
                            {
                                result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                                return result;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        /// <summary>
        /// 正常分选等级的更新,没有Plc那边的直流数据,只有正常数据.这里是一片一片的去统计的,所以这里基本上如果要增加总分选汇总数量也是+1
        /// 但是这个片子如果出现了异常,又是Plc去统计的所以,异常片这里不做统计.
        /// </summary>
        /// <param name="crystalNumber">当前的晶棒编号</param>
        /// <param name="levelIndex">对应的等级</param>
        /// <param name="isOk">是否是正常分选</param>
        /// <returns>如果成功,返回分选汇总的所有片数,主要是给workingInfo来使用,确保两边的数据保持一致</returns>
        internal static DataResult UpdateCrystalLevelCountTbNormal(string crystalNumber, int levelIndex)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.CrystalLevelCountTb;
            try
            {
                lock (obj02)
                {

                    // 1. 先去查询这条数据是否存在,正常分选,非缺数直流,非直流,就是正常统计值.这里更新的时候,每次累加正常分选汇总即可.
                    // 2. 正常分选汇总 + 直流 + 缺数直流 = 总的汇总.
                    string sqlQuery = $"Select [Count] From {tableName} Where [CrystalNumber] = @CrystalNumber And [LevelIndex] = @LevelIndex";
                    SqlParameter[] queryParameters = new SqlParameter[]
                    {
                        new SqlParameter($"@CrystalNumber",crystalNumber),
                        new SqlParameter($"@LevelIndex",levelIndex)
                    };
                    DataTable table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                    if (table.Rows.Count <= 0)
                    {
                        result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                    }
                    else
                    {
                        // 将查询的数据拿到,然后去更新成新的值
                        string sqlCount = table.Rows[0].Field<string>("Count")!;
                        int newCount;
                        bool success = int.TryParse(sqlCount, out int number);
                        if (success)
                        {
                            // 如果是直流,就要直接使用PLC给出的统计的值.
                            newCount = (number + 1);
                        }
                        else
                        {
                            newCount = 1;
                        }

                        // 去更新数据,本次等级的值.
                        string sqlUpdate = $"UPDATE [dbo].[{tableName}] SET [Count] = @Count Where [CrystalNumber] = @CrystalNumber And [LevelIndex] = @LevelIndex ;";
                        SqlParameter[] updateParameters = new SqlParameter[]
                        {
                            new SqlParameter("@Count",newCount),
                            new SqlParameter("@CrystalNumber",crystalNumber),
                            new SqlParameter("@LevelIndex",levelIndex)
                        };
                        int count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                        if (count <= 0)
                        {
                            result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                            return result;
                        }

                        if (levelIndex < 30)
                        {
                            // 1.更新正常分选 和 总分选的值.
                            queryParameters = new SqlParameter[]
                            {
                                new SqlParameter($"@CrystalNumber",crystalNumber),
                                new SqlParameter($"@LevelIndex",39)
                            };

                            table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                            if (table.Rows.Count <= 0)
                            {
                                result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                            }
                            else
                            {
                                // 将查询的数据拿到,然后去更新成新的值
                                sqlCount = table.Rows[0].Field<string>("Count")!;
                                success = int.TryParse(sqlCount, out int number02);
                                if (success)
                                {
                                    // 如果是直流,就要直接使用PLC给出的统计的值.
                                    newCount = (number02 + 1);
                                }
                                else
                                {
                                    newCount = 1;
                                }

                                updateParameters = new SqlParameter[]
                                {

                                    new SqlParameter("@Count",newCount),
                                    new SqlParameter("@CrystalNumber",crystalNumber),
                                    new SqlParameter("@LevelIndex",39) // 正常分选汇总的值加1.
                                };

                                // 更新正常分选的值.
                                count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                                if (count <= 0)
                                {
                                    result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                                    return result;
                                }
                            }
                        }


                        queryParameters = new SqlParameter[]
                            {
                                new SqlParameter($"@CrystalNumber",crystalNumber),
                                new SqlParameter($"@LevelIndex",38)
                            };

                        table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                        if (table.Rows.Count <= 0)
                        {
                            result.Message = $"{tableName} 表中不存在数据 {crystalNumber},{levelIndex}";
                        }
                        else
                        {
                            // 将查询的数据拿到,然后去更新成新的值
                            sqlCount = table.Rows[0].Field<string>("Count")!;
                            success = int.TryParse(sqlCount, out int number03);
                            if (success)
                            {
                                // 如果是直流,就要直接使用PLC给出的统计的值.
                                newCount = (number03 + 1);
                            }
                            else
                            {
                                newCount = 1;
                            }

                            updateParameters = new SqlParameter[]
                            {

                                    new SqlParameter("@Count",newCount),
                                    new SqlParameter("@CrystalNumber",crystalNumber),
                                    new SqlParameter("@LevelIndex",38)
                            };

                            // 更新正常分选的值.
                            count = SqlHelper.ExecuteNonQuery(sqlUpdate, updateParameters);
                            if (count <= 0)
                            {
                                result.Message = $"数据更新失败,请检查数据库连接是否正常!";
                                return result;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }



        #endregion


        #region 3. 初始化数据库,根据集合插入数据到CouontTb中
        public static DataResult InsertDataToCrystalLevelCountTb(List<CrystalLevelCountEntity> crystalLevelCounts)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.CrystalLevelCountTb;
            try
            {
                string sql = $"INSERT INTO [DBO].{tableName} ([CrystalNumber], [LevelIndex], [LevelType], [Count]) " +
                                    $"VALUES (@CrystalNumber, @LevelIndex, @LevelType, @Count);";



                foreach (var data in crystalLevelCounts)
                {
                    SqlParameter[] parameters = new SqlParameter[]
                    {
                        new SqlParameter("@CrystalNumber",SqlDbType.VarChar),
                        new SqlParameter("@LevelIndex",SqlDbType.Int),
                        new SqlParameter("@LevelType",SqlDbType.VarChar),
                        new SqlParameter("@Count",SqlDbType.VarChar)
                    };
                    parameters[0].Value = data.CrystalNumber;
                    parameters[1].Value = data.LevelIndex;
                    parameters[2].Value = data.LevelType;
                    parameters[3].Value = data.Count;
                    var count = SqlHelper.ExecuteNonQuery(sql, parameters);
                    if (count < 0)
                    {
                        result.Message = $"数据库{tableName} 数据插入失败!";
                        return result;
                    }
                }
                result.State = true;
                result.Message = $"表{tableName} 数据插入成功!";

            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        #endregion

        #region 4. 插入数据到数据库中
        // 新增用户,先去查询如果用户名已经存在,就提示用户已经存在,重新命名
        public static DataResult AddUserInfoToDb(string queryField, string queryVal, List<string> insertFields, List<string> insertVals)
        {
            string tableName = TableNames.UserTb;
            DataResult result = new DataResult();
            try
            {
                string sql = $"Select * from {tableName} Where [{queryField}] = @{queryField};";
                SqlParameter[] insertParameters = new SqlParameter[]
                {
                    new SqlParameter($"@{queryField}",queryVal),
                };
                int count = SqlHelper.ExcuteGetCount(sql, insertParameters);
                if (count > 0)
                {
                    result.Message = $"用户名{queryVal} 已经存在,请重新输入用户名";
                }
                else
                {
                    sql = $"INSERT INTO {tableName} (";
                    foreach (var field in insertFields)
                    {
                        sql += $" [{field}],";
                    }
                    sql = sql.RemoveLast(1); // 移除掉最后的那个逗号
                    sql += ")";
                    sql += $" Values(";
                    foreach (var field in insertFields)
                    {
                        sql += $"@{field},";
                    }
                    sql = sql.RemoveLast(1);
                    sql += ");";

                    List<SqlParameter> newParameters = new List<SqlParameter>();
                    for (int i = 0; i < insertFields.Count(); i++)
                    {
                        newParameters.Add(new SqlParameter($"@{insertFields[i]}", SqlDbType.VarChar) { Value = insertVals[i] });
                    }
                    count = SqlHelper.ExecuteNonQuery(sql, newParameters.ToArray());
                    if (count > 0)
                    {
                        result.State = true;
                    }
                    else
                    {
                        result.Message = "新用户插入失败!";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 根据用户名去删除数据表中的某个用户.用户名唯一,在创建的时候都限制了.
        /// </summary>
        /// <param name="v"></param>
        /// <param name="editorUserName"></param>
        /// <exception cref="NotImplementedException"></exception>
        internal static DataResult DeleteUserDbByUsername(string deleteField, string? editorUserName)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.UserTb;
            try
            {
                string sql = $"Delete From {tableName} Where [{deleteField}]=@{deleteField} ;";
                SqlParameter[] deleteParameters = new SqlParameter[]
                 {
                    new SqlParameter($"@{deleteField}",editorUserName),
                 };

                int count = SqlHelper.ExecuteNonQuery(sql, deleteParameters);
                if (count < 0)
                {
                    result.Message = "数据删除失败,数据不存在";
                }
                else
                {
                    result.State = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        #endregion

        /// <summary>
        /// 根据表名去删除对应的表中的内容,并且数据Id从0开始
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static DataResult DeleteTableByName(string tableName)
        {
            DataResult result = new DataResult();
            try
            {
                string sql = $"Truncate Table {tableName} ;";
                SqlHelper.ExecuteNonQuery(sql, null);
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 插入一条报警记录
        /// </summary>
        /// <param name="alarm"></param>
        /// <exception cref="NotImplementedException"></exception>
        internal static void InsertAlarmRecord(AlarmRecordEntity alarm, bool isInsert)
        {
            string tableName = TableNames.AlarmRecordTb;
            try
            {
                // 插入之前先判断一下表是否存在.
                string sql = $"IF NOT EXISTS(SELECT* FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{tableName}]') AND type in (N'U'))" +
                                   $"BEGIN " +
                                   $"CREATE TABLE[dbo].[{tableName}](" +
                                   $"[Id] INT IDENTITY(1,1) PRIMARY KEY," +
                                   $"[AlarmCode] VARCHAR(20) NOT NULL," +
                                   $"[Content] VARCHAR(300) ," +
                                   $"[SolutionHelp] VARCHAR(200)," +
                                   $"[CreateTime] VARCHAR(50));" +
                                   $" END";
                SqlHelper.ExecuteNonQuery(sql, null);

                // 先去查询这个报警信息是否存在,如果存在了,去找第一条数据
                string sqlQuery = $"Select * from {tableName} where [AlarmCode] = @AlarmCode Order By Id Desc";
                SqlParameter[] queryParameters = new SqlParameter[]
                {
                        new SqlParameter($"@AlarmCode",alarm.AlarmCode),
                };
                DataTable table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                if (table.Rows.Count > 0 && !isInsert)
                {
                    // 如果数据已经存在,取出来第一条,判断时间间隔是否在1分钟以内,如果在一分钟以内,就认为是相同的报警,删除掉该条报警,然后重新插入新的报警就行了.
                    string latestAlarm = table.Rows[0].Field<string>("CreateTime")!;
                    // 根据两个字符串,去判断时间间隔是否是在1分钟以内
                    TimeSpan duration = DateTime.Parse(latestAlarm) - DateTime.Now;
                    // 如果间隔小于90秒,就认为是同一次报警,就将旧的报警删除,插入新的报警
                    if (duration.TotalSeconds < 30)
                    {

                        string sqlDelete = $"Delete From {tableName} Where [AlarmCode] = @AlarmCode And [CreateTime] = @CreateTime;";
                        SqlParameter[] parametersDelte = new SqlParameter[]
                        {
                            new SqlParameter($"@AlarmCode",alarm.AlarmCode),
                            new SqlParameter($"@CreateTime",latestAlarm),
                        };
                        int ret2 = SqlHelper.ExecuteNonQuery(sqlDelete, parametersDelte);
                        if (ret2 <= 0)
                        {
                            string infoMessage = $"数据表{tableName} 删除对应 AlarmCode = {alarm.AlarmCode} And CreateTime = {latestAlarm} 的数据失败!";
                            throw new Exception(infoMessage);
                        }
                    }
                }

                sql = $"INSERT INTO [DBO].{tableName} ([AlarmCode], [Content],[SolutionHelp],[CreateTime]) " +
                     $"VALUES (@AlarmCode,@Content,@SolutionHelp,@CreateTime);";

                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@AlarmCode",SqlDbType.VarChar){Value = alarm.AlarmCode},
                    new SqlParameter("@Content",SqlDbType.VarChar){Value = alarm.Content},
                    new SqlParameter("@SolutionHelp",SqlDbType.VarChar){Value=alarm.SolutionHelp},
                    new SqlParameter("@CreateTime",SqlDbType.VarChar){Value= DateTimeHelper.GetTimeNowForSql()}
                };
                int ret = SqlHelper.ExecuteNonQuery(sql, parameters);
                if (ret <= 0)
                {
                    string infoMessage = $"数据表{tableName} 插入数据失败!";
                    throw new Exception(infoMessage);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"{tableName} 数据表创建失败: {ex.Message}");
            }
        }

        internal static void InsertAlarmMainShow(AlarmRecordEntity alarm, bool isInsert)
        {
            string tableName = TableNames.AlarmMainShowTb;
            try
            {
                // 插入之前先判断一下表是否存在.
                string sql = $"IF NOT EXISTS(SELECT* FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{tableName}]') AND type in (N'U'))" +
                                   $"BEGIN " +
                                   $"CREATE TABLE[dbo].[{tableName}](" +
                                   $"[Id] INT IDENTITY(1,1) PRIMARY KEY," +
                                   $"[AlarmCode] VARCHAR(20) NOT NULL," +
                                   $"[Content] VARCHAR(300) ," +
                                   $"[SolutionHelp] VARCHAR(200)," +
                                   $"[CreateTime] VARCHAR(50));" +
                                   $" END";
                SqlHelper.ExecuteNonQuery(sql, null);

                // 先去查询这个报警信息是否存在,如果存在了,去找第一条数据
                string sqlQuery = $"Select * from {tableName} where [AlarmCode] = @AlarmCode Order By Id Desc";
                SqlParameter[] queryParameters = new SqlParameter[]
                {
                        new SqlParameter($"@AlarmCode",alarm.AlarmCode),
                };
                DataTable table = DataAccess.GetDataTables(sqlQuery, queryParameters);
                if (table.Rows.Count > 0 && !isInsert)
                {
                    // 如果数据已经存在,取出来第一条,判断时间间隔是否在1分钟以内,如果在一分钟以内,就认为是相同的报警,删除掉该条报警,然后重新插入新的报警就行了.
                    string latestAlarm = table.Rows[0].Field<string>("CreateTime")!;
                    // 根据两个字符串,去判断时间间隔是否是在1分钟以内
                    TimeSpan duration = DateTime.Parse(latestAlarm) - DateTime.Now;
                    // 如果间隔小于90秒,就认为是同一次报警,就将旧的报警删除,插入新的报警
                    if (duration.TotalSeconds < 30)
                    {

                        string sqlDelete = $"Delete From {tableName} Where [AlarmCode] = @AlarmCode And [CreateTime] = @CreateTime;";
                        SqlParameter[] parametersDelte = new SqlParameter[]
                        {
                            new SqlParameter($"@AlarmCode",alarm.AlarmCode),
                            new SqlParameter($"@CreateTime",latestAlarm),
                        };
                        int ret2 = SqlHelper.ExecuteNonQuery(sqlDelete, parametersDelte);
                        if (ret2 <= 0)
                        {
                            string infoMessage = $"数据表{tableName} 删除对应 AlarmCode = {alarm.AlarmCode} And CreateTime = {latestAlarm} 的数据失败!";
                            throw new Exception(infoMessage);
                        }
                    }
                }

                sql = $"INSERT INTO [DBO].{tableName} ([AlarmCode], [Content],[SolutionHelp],[CreateTime]) " +
                     $"VALUES (@AlarmCode,@Content,@SolutionHelp,@CreateTime);";

                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@AlarmCode",SqlDbType.VarChar){Value = alarm.AlarmCode},
                    new SqlParameter("@Content",SqlDbType.VarChar){Value = alarm.Content},
                    new SqlParameter("@SolutionHelp",SqlDbType.VarChar){Value=alarm.SolutionHelp},
                    new SqlParameter("@CreateTime",SqlDbType.VarChar){Value= DateTimeHelper.GetTimeNowForSql()}
                };
                int ret = SqlHelper.ExecuteNonQuery(sql, parameters);
                if (ret <= 0)
                {
                    string infoMessage = $"数据表{tableName} 插入数据失败!";
                    throw new Exception(infoMessage);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"{tableName} 数据表创建失败: {ex.Message}");
            }
        }

        public static void DeleteDataByFeild(string tableName, string queryField, string queryVal)
        {
            try
            {
                // 1. 先去查询这个表是否存在

                string sql = $"Delete From {tableName} Where [{queryField}]= @{queryField};";

                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter($"@{queryField}",SqlDbType.VarChar){Value = queryVal},
                };
                int ret = SqlHelper.ExecuteNonQuery(sql, parameters);
                if (ret <= 0)
                {
                    string infoMessage = $"数据表{tableName} 删除对应{queryField} = {queryVal} 的数据失败!";
                    throw new Exception(infoMessage);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogType.Exception, $"{tableName} 数据表删除对应数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 将上一单的信息保存到结果查询中去.就是汇总的一些信息.
        /// </summary>
        /// <param name="lastCrystalNumber"></param>
        /// <returns></returns>
        internal static DataResult SaveCrystalRecordByCrystalNumber(string? crystalNumber)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.CrystalLevelCountTb;
            try
            {
                string sql = $"Select * from {tableName} where [CrystalNumber] = @CrystalNumber Order By LevelIndex";
                SqlParameter[] queryParameters = new SqlParameter[]
                {
                        new SqlParameter($"@CrystalNumber",crystalNumber),
                };
                DataTable table = DataAccess.GetDataTables(sql, queryParameters);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"{tableName} 表中不存在数据 晶棒编号为{crystalNumber},查询上一单数据失败";
                }
                else
                {
                    // 将查询的数据拿到,然后去更新成新的值
                    List<CrystalLevelCountEntity> levelCountList = (from q in table.AsEnumerable()
                                                                    select new CrystalLevelCountEntity()
                                                                    {
                                                                        CrystalNumber = q.Field<string>("CrystalNumber"),
                                                                        LevelIndex = q.Field<int>("LevelIndex"),
                                                                        LevelType = q.Field<string>("LevelType"),
                                                                        Count = q.Field<string>("Count")
                                                                    }).ToList();

                    // 注意之类更新的是结果表
                    tableName = TableNames.CrystalRecordTb;
                    sql = $"INSERT INTO [DBO].{tableName} ([CrystalNumber], [ProductionDate],[Lv01],[Lv02],[Lv03],[Lv04],[Lv05],[Lv06],[Lv07],[Lv08],[Lv09],[Lv10],[Lv11]," +
                        $"[Lv12],[Lv13],[Lv14],[Lv15],[Lv16],[Lv17],[Lv18],[Lv19],[Lv20],[Lv21],[Lv22],[Lv23],[Lv24],[Lv25],[Lv26]) " +
                        $"VALUES (@CrystalNumber,@ProductionDate,@Lv01,@Lv02,@Lv03,@Lv04,@Lv05,@Lv06,@Lv07,@Lv08,@Lv09,@Lv10,@Lv11,@Lv12,@Lv13,@Lv14,@Lv15," +
                        $"@Lv16,@Lv17,@Lv18,@Lv19,@Lv20,@Lv21,@Lv22,@Lv23,@Lv24,@Lv25,@Lv26);";

                    int normalDetectedCount = GlobalValues.NormalDetectedTotalCounts; // 正常的检测等级的个数.




                    SqlParameter[] parameters = null!;
                    if (normalDetectedCount == 13)
                    {
                        parameters = new SqlParameter[]
                        {
                            new SqlParameter("@CrystalNumber",SqlDbType.VarChar){Value = crystalNumber},
                            new SqlParameter("@ProductionDate",SqlDbType.VarChar){Value = DateTimeHelper.GetTimeNowForSql()},
                            new SqlParameter("@Lv01",SqlDbType.VarChar){Value= levelCountList[0].Count},
                            new SqlParameter("@Lv02",SqlDbType.VarChar){Value=levelCountList[1].Count},
                            new SqlParameter("@Lv03",SqlDbType.VarChar){Value= levelCountList[2].Count },
                            new SqlParameter("@Lv04",SqlDbType.VarChar){Value= levelCountList[3].Count},
                            new SqlParameter("@Lv05",SqlDbType.VarChar){Value=levelCountList[4].Count},
                            new SqlParameter("@Lv06",SqlDbType.VarChar){Value= levelCountList[5].Count},
                            new SqlParameter("@Lv07",SqlDbType.VarChar){Value= levelCountList[6].Count},
                            new SqlParameter("@Lv08",SqlDbType.VarChar){Value=levelCountList[7].Count},
                            new SqlParameter("@Lv09",SqlDbType.VarChar){Value= levelCountList[8].Count},
                            new SqlParameter("@Lv10",SqlDbType.VarChar){Value= levelCountList[9].Count},
                            new SqlParameter("@Lv11",SqlDbType.VarChar){Value=levelCountList[10].Count},
                            new SqlParameter("@Lv12",SqlDbType.VarChar){Value= levelCountList[11].Count},
                            new SqlParameter("@Lv13",SqlDbType.VarChar){Value= levelCountList[12].Count},
                            new SqlParameter("@Lv14",SqlDbType.VarChar){Value="0"},
                            new SqlParameter("@Lv15",SqlDbType.VarChar){Value= "0"},
                            new SqlParameter("@Lv16",SqlDbType.VarChar){Value= "0"},
                            new SqlParameter("@Lv17",SqlDbType.VarChar){Value=levelCountList[13].Count},
                            new SqlParameter("@Lv18",SqlDbType.VarChar){Value= levelCountList[14].Count},
                            new SqlParameter("@Lv19",SqlDbType.VarChar){Value= levelCountList[15].Count},
                            new SqlParameter("@Lv20",SqlDbType.VarChar){Value=levelCountList[16].Count},
                            new SqlParameter("@Lv21",SqlDbType.VarChar){Value= levelCountList[17].Count},
                            new SqlParameter("@Lv22",SqlDbType.VarChar){Value= levelCountList[18].Count},
                            new SqlParameter("@Lv23",SqlDbType.VarChar){Value=levelCountList[19].Count},
                            new SqlParameter("@Lv24",SqlDbType.VarChar){Value= levelCountList[20].Count},
                            new SqlParameter("@Lv25",SqlDbType.VarChar){Value= levelCountList[21].Count},
                            new SqlParameter("@Lv26",SqlDbType.VarChar){Value= levelCountList[22].Count},
                        };
                    }
                    else if (normalDetectedCount == 14)
                    {
                        parameters = new SqlParameter[]
                        {
                            new SqlParameter("@CrystalNumber",SqlDbType.VarChar){Value = crystalNumber},
                            new SqlParameter("@ProductionDate",SqlDbType.VarChar){Value = DateTimeHelper.GetTimeNowForSql()},
                            new SqlParameter("@Lv01",SqlDbType.VarChar){Value= levelCountList[0].Count},
                            new SqlParameter("@Lv02",SqlDbType.VarChar){Value=levelCountList[1].Count},
                            new SqlParameter("@Lv03",SqlDbType.VarChar){Value= levelCountList[2].Count },
                            new SqlParameter("@Lv04",SqlDbType.VarChar){Value= levelCountList[3].Count},
                            new SqlParameter("@Lv05",SqlDbType.VarChar){Value=levelCountList[4].Count},
                            new SqlParameter("@Lv06",SqlDbType.VarChar){Value= levelCountList[5].Count},
                            new SqlParameter("@Lv07",SqlDbType.VarChar){Value= levelCountList[6].Count},
                            new SqlParameter("@Lv08",SqlDbType.VarChar){Value=levelCountList[7].Count},
                            new SqlParameter("@Lv09",SqlDbType.VarChar){Value= levelCountList[8].Count},
                            new SqlParameter("@Lv10",SqlDbType.VarChar){Value= levelCountList[9].Count},
                            new SqlParameter("@Lv11",SqlDbType.VarChar){Value=levelCountList[10].Count},
                            new SqlParameter("@Lv12",SqlDbType.VarChar){Value= levelCountList[11].Count},
                            new SqlParameter("@Lv13",SqlDbType.VarChar){Value= levelCountList[12].Count},
                            new SqlParameter("@Lv14",SqlDbType.VarChar){Value=levelCountList[13].Count},
                            new SqlParameter("@Lv15",SqlDbType.VarChar){Value= "0"},
                            new SqlParameter("@Lv16",SqlDbType.VarChar){Value= "0"},
                            new SqlParameter("@Lv17",SqlDbType.VarChar){Value=levelCountList[14].Count},
                            new SqlParameter("@Lv18",SqlDbType.VarChar){Value= levelCountList[15].Count},
                            new SqlParameter("@Lv19",SqlDbType.VarChar){Value= levelCountList[16].Count},
                            new SqlParameter("@Lv20",SqlDbType.VarChar){Value=levelCountList[17].Count},
                            new SqlParameter("@Lv21",SqlDbType.VarChar){Value= levelCountList[18].Count},
                            new SqlParameter("@Lv22",SqlDbType.VarChar){Value= levelCountList[19].Count},
                            new SqlParameter("@Lv23",SqlDbType.VarChar){Value=levelCountList[20].Count},
                            new SqlParameter("@Lv24",SqlDbType.VarChar){Value= levelCountList[21].Count},
                            new SqlParameter("@Lv25",SqlDbType.VarChar){Value= levelCountList[22].Count},
                            new SqlParameter("@Lv26",SqlDbType.VarChar){Value= levelCountList[23].Count},
                        };
                    }
                    else if (normalDetectedCount == 15)
                    {
                        parameters = new SqlParameter[]
                        {
                            new SqlParameter("@CrystalNumber",SqlDbType.VarChar){Value = crystalNumber},
                            new SqlParameter("@ProductionDate",SqlDbType.VarChar){Value = DateTimeHelper.GetTimeNowForSql()},
                            new SqlParameter("@Lv01",SqlDbType.VarChar){Value= levelCountList[0].Count},
                            new SqlParameter("@Lv02",SqlDbType.VarChar){Value=levelCountList[1].Count},
                            new SqlParameter("@Lv03",SqlDbType.VarChar){Value= levelCountList[2].Count },
                            new SqlParameter("@Lv04",SqlDbType.VarChar){Value= levelCountList[3].Count},
                            new SqlParameter("@Lv05",SqlDbType.VarChar){Value=levelCountList[4].Count},
                            new SqlParameter("@Lv06",SqlDbType.VarChar){Value= levelCountList[5].Count},
                            new SqlParameter("@Lv07",SqlDbType.VarChar){Value= levelCountList[6].Count},
                            new SqlParameter("@Lv08",SqlDbType.VarChar){Value=levelCountList[7].Count},
                            new SqlParameter("@Lv09",SqlDbType.VarChar){Value= levelCountList[8].Count},
                            new SqlParameter("@Lv10",SqlDbType.VarChar){Value= levelCountList[9].Count},
                            new SqlParameter("@Lv11",SqlDbType.VarChar){Value=levelCountList[10].Count},
                            new SqlParameter("@Lv12",SqlDbType.VarChar){Value= levelCountList[11].Count},
                            new SqlParameter("@Lv13",SqlDbType.VarChar){Value= levelCountList[12].Count},
                            new SqlParameter("@Lv14",SqlDbType.VarChar){Value=levelCountList[13].Count},
                            new SqlParameter("@Lv15",SqlDbType.VarChar){Value= levelCountList[14].Count},
                            new SqlParameter("@Lv16",SqlDbType.VarChar){Value= "0"},
                            new SqlParameter("@Lv17",SqlDbType.VarChar){Value=levelCountList[15].Count},
                            new SqlParameter("@Lv18",SqlDbType.VarChar){Value= levelCountList[16].Count},
                            new SqlParameter("@Lv19",SqlDbType.VarChar){Value= levelCountList[17].Count},
                            new SqlParameter("@Lv20",SqlDbType.VarChar){Value=levelCountList[18].Count},
                            new SqlParameter("@Lv21",SqlDbType.VarChar){Value= levelCountList[19].Count},
                            new SqlParameter("@Lv22",SqlDbType.VarChar){Value= levelCountList[20].Count},
                            new SqlParameter("@Lv23",SqlDbType.VarChar){Value=levelCountList[21].Count},
                            new SqlParameter("@Lv24",SqlDbType.VarChar){Value= levelCountList[22].Count},
                            new SqlParameter("@Lv25",SqlDbType.VarChar){Value= levelCountList[23].Count},
                            new SqlParameter("@Lv26",SqlDbType.VarChar){Value= levelCountList[24].Count},

                        };
                    }
                    else if (normalDetectedCount == 16)
                    {
                        parameters = new SqlParameter[]
                        {
                            new SqlParameter("@CrystalNumber",SqlDbType.VarChar){Value = crystalNumber},
                            new SqlParameter("@ProductionDate",SqlDbType.VarChar){Value = DateTimeHelper.GetTimeNowForSql()},
                            new SqlParameter("@Lv01",SqlDbType.VarChar){Value= levelCountList[0].Count},
                            new SqlParameter("@Lv02",SqlDbType.VarChar){Value=levelCountList[1].Count},
                            new SqlParameter("@Lv03",SqlDbType.VarChar){Value= levelCountList[2].Count},
                            new SqlParameter("@Lv04",SqlDbType.VarChar){Value= levelCountList[3].Count},
                            new SqlParameter("@Lv05",SqlDbType.VarChar){Value=levelCountList[4].Count},
                            new SqlParameter("@Lv06",SqlDbType.VarChar){Value= levelCountList[5].Count},
                            new SqlParameter("@Lv07",SqlDbType.VarChar){Value= levelCountList[6].Count},
                            new SqlParameter("@Lv08",SqlDbType.VarChar){Value=levelCountList[7].Count},
                            new SqlParameter("@Lv09",SqlDbType.VarChar){Value= levelCountList[8].Count},
                            new SqlParameter("@Lv10",SqlDbType.VarChar){Value= levelCountList[9].Count},
                            new SqlParameter("@Lv11",SqlDbType.VarChar){Value=levelCountList[10].Count},
                            new SqlParameter("@Lv12",SqlDbType.VarChar){Value= levelCountList[11].Count},
                            new SqlParameter("@Lv13",SqlDbType.VarChar){Value= levelCountList[12].Count},
                            new SqlParameter("@Lv14",SqlDbType.VarChar){Value=levelCountList[13].Count},
                            new SqlParameter("@Lv15",SqlDbType.VarChar){Value= levelCountList[14].Count},
                            new SqlParameter("@Lv16",SqlDbType.VarChar){Value= levelCountList[15].Count},
                            new SqlParameter("@Lv17",SqlDbType.VarChar){Value=levelCountList[16].Count},
                            new SqlParameter("@Lv18",SqlDbType.VarChar){Value= levelCountList[17].Count},
                            new SqlParameter("@Lv19",SqlDbType.VarChar){Value= levelCountList[18].Count},
                            new SqlParameter("@Lv20",SqlDbType.VarChar){Value=levelCountList[19].Count},
                            new SqlParameter("@Lv21",SqlDbType.VarChar){Value= levelCountList[20].Count},
                            new SqlParameter("@Lv22",SqlDbType.VarChar){Value= levelCountList[21].Count},
                            new SqlParameter("@Lv23",SqlDbType.VarChar){Value=levelCountList[22].Count},
                            new SqlParameter("@Lv24",SqlDbType.VarChar){Value= levelCountList[23].Count},
                            new SqlParameter("@Lv25",SqlDbType.VarChar){Value= levelCountList[24].Count},
                            new SqlParameter("@Lv26",SqlDbType.VarChar){Value= levelCountList[25].Count},

                        };
                    }
                    int ret = SqlHelper.ExecuteNonQuery(sql, parameters);
                    if (ret <= 0)
                    {
                        result.Message = $"数据表{tableName} 插入数据失败,保存上一单检测数据失败!";
                    }
                }
                result.Message = $"数据表{tableName} 插入数据成功,保存上一单检测数据成功!!";
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 查询获取所有的表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal static DataResult<List<string>> GetTotalCrystalNamesByRecordTb()
        {
            DataResult<List<string>> result = new DataResult<List<string>>();
            string tableName = TableNames.CrystalRecordTb;
            try
            {
                string sql = $"Select [CrystalNumber] from {tableName} Order By Id";
                DataTable dt = DataAccess.GetDataTables(sql, null);
                if (dt.Rows.Count < 0)
                {
                    result.Message = $"数据表{tableName}不存在";
                    return result;
                }
                List<string> crystalNames = new List<string>();
                crystalNames = (from q in dt.AsEnumerable()
                                select q.Field<string>("CrystalNumber")).ToList();
                result.Data = crystalNames;
                result.State = true;
                return result;

            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
        }

        internal static DataResult<List<VisionOffsetEntity>> GetVisionOffsetData()
        {
            DataResult<List<VisionOffsetEntity>> result = new DataResult<List<VisionOffsetEntity>>();
            string tableName = TableNames.VisionOffsetTb;
            try
            {
                string sql = $"Select * from {tableName} Order By Id";
                DataTable dt = DataAccess.GetDataTables(sql, null);
                if (dt.Rows.Count < 0)
                {
                    result.Message = $"数据表{tableName}不存在";
                    return result;
                }
                result.Data = (from q in dt.AsEnumerable()
                               select new VisionOffsetEntity
                               {
                                   Id = q.Field<int>("Id"),
                                   ModuleName = q.Field<string>("ModuleName"),
                                   OptionName = q.Field<string>("OptionName"),
                                   OffsetK = q.Field<double>("OffsetK"),
                                   OffsetB = q.Field<double>("OffsetB")
                               }).ToList();
                result.State = true;
                return result;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
        }

        /// <summary>
        /// 根据晶棒编号和流水号获取单个流水号的所有信息,好写入到数据库中
        /// </summary>
        /// <param name="crystalNumberCurrent"></param>
        /// <param name="waferId"></param>
        /// <returns></returns>
        internal static DataResult<List<string>> GetSingleDataByWaferId(string? crystalNumberCurrent, string waferId)
        {
            DataResult<List<string>> result = new DataResult<List<string>>();
            string tableName = TableManager.GetTableNameByCrystalNumber(crystalNumberCurrent!);
            try
            {
                string sql = $"Select  * from {tableName} Where [WaferId] = @WaferId  Order By Id Desc";
                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@WaferId",waferId),
                };

                DataTable dt = DataAccess.GetDataTables(sql, parameters);
                if (dt.Rows.Count < 0)
                {
                    result.Message = $"数据表{tableName}不存在";
                    return result;
                }
                string dataAdded;
                List<string> resultStr = new List<string>();
                DataRow data = dt.Rows[0];
                resultStr.Add(data.Field<string>("DetectedTime")!);
                resultStr.Add(data.Field<string>("ProductionDate")!);
                resultStr.Add(data.Field<string>("WaferId")!);
                resultStr.Add(data.Field<string>("CutNumber")!);
                resultStr.Add(data.Field<string>("CrystalNumber")!);
                resultStr.Add(data.Field<string>("PositionNumber")!);
                resultStr.Add(data.Field<string>("ProductionLot")!);
                resultStr.Add(data.Field<string>("FlowerNumber")!);
                resultStr.Add(data.Field<string>("DetectionRecipe")!);
                resultStr.Add(data.Field<string>("DetectedLevel")!);
                resultStr.Add(data.Field<string>("LevelType")!);
                resultStr.Add(data.Field<string>("TypeDescription")!);
                resultStr.Add(data.Field<string>("BoxNumber")!);
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ThicknessAver")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("TTV")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LineTraceMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("Warping")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ResistivityAver")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ResistivityMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ResistivityMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthXMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthXMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthYMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthYMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthX")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LengthY")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("DiagonalLeftStart")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("DialonalRightStart")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ChamferMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ChamferMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("UpDownParallel")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftRightParallel")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SquareLineMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SquareLineMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("VerticalAngleMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("VerticalAngleMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftTopCharmfer")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("RightTopCharmfer")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftBottomCharmfer")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("RightBottomCharmfer")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftTopAngle")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("RightTopAngle")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftBottomAngle")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("RightBottomAngle")!));
                // 1. 先判断是否为空字符串
                dataAdded = data.Field<string>("FrontEdgeBreakExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("FrontEdgeBreakNum")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("FrontEdgeBreakArea")!));
                dataAdded = data.Field<string>("BackEdgeBreakExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("BackEdgeBreakNum")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("BackEdgeBreakArea")!));
                dataAdded = data.Field<string>("LeftEdgeBreakExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftEdgeBreakNum")!));
                dataAdded = data.Field<string>("LeftSurfaceBreakExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LeftSurfaceBreakNum")!));

                dataAdded = data.Field<string>("RightEdgeBreakExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("RightEdgeBreakNum")!));

                dataAdded = data.Field<string>("RightSurfaceBreakExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("RightSurfaceBreakNum")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ThicknessMin")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("ThicknessMax")!));

                dataAdded = data.Field<string>("IsDenseLine")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "否" : "是");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LineTraceUpNum")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LineTraceUpMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LineTraceDownNum")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LineTraceDownMax")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("LineTraceCount")!));
                dataAdded = data.Field<string>("SumdgeUpExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SmudgeUpArea")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SumdgeUpNum")!));

                dataAdded = data.Field<string>("SumdgeUpReverse")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "否" : "是");
                }

                dataAdded = data.Field<string>("SumdgeUpHoleExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                dataAdded = data.Field<string>("HoleExistUp")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                dataAdded = data.Field<string>("SumdgeDownExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SumdgeDownArea")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SumdgeDownNum")!));

                dataAdded = data.Field<string>("SumdgeDownReverse")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "否" : "是");
                }

                dataAdded = data.Field<string>("HoleExistDown")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                dataAdded = data.Field<string>("SumdgeDownHoleExist")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                dataAdded = data.Field<string>("SubfissureExist01")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureArea01")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureNum01")!));

                dataAdded = data.Field<string>("SubfissureBreakExist01")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }

                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureBreakArea01")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureBreakNum01")!));

                dataAdded = data.Field<string>("SubfissureHoleExist01")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureHoleNum01")!));

                dataAdded = data.Field<string>("SubfissureExist02")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureArea02")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureNum02")!));
                dataAdded = data.Field<string>("SubfissureBreakExist02")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureBreakArea02")!));
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureBreakNum02")!));
                dataAdded = data.Field<string>("SubfissureHoleExist02")!;
                if (string.IsNullOrEmpty(dataAdded))
                {
                    resultStr.Add("");
                }
                else
                {
                    resultStr.Add(dataAdded.Equals("0") ? "无" : "有");
                }
                resultStr.Add(CsvHelper.GetNumberValForCsv(data.Field<string>("SubfissureHoleNum02")!));
                result.Data = resultStr;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }

            return result;
        }

        /// <summary>
        /// 更新WorkingInfo中的分选汇总的总数,这里之前的逻辑用不了,是因为有问题.要实时的加1.
        /// </summary>
        /// <param name="list"></param>
        internal static DataResult UpdateWorkingInfoTotalCountFromPc()
        {
            DataResult result = new DataResult();
            string tableName = TableNames.WorkingInfoTb;
            try
            {
                string sql = $"select [TotalCountFromPc] from {tableName}";
                DataTable table = DataAccess.GetDataTables(sql, null);
                if (table.Rows.Count <= 0)
                {
                    result.Message = $"数据表{tableName}不存在或者是表中无数据";
                    return result;
                }
                int totalCount = int.Parse(table.Rows[0].Field<string>("TotalCountFromPc")!) + 1;
                int queryId = 1;
                sql = $"UPDATE [dbo].[{tableName}] SET [TotalCountFromPc] = @TotalCountFromPc Where [WorkingId] = @WorkingId;";
                List<SqlParameter> updateParameters = new List<SqlParameter>()
                {
                    new SqlParameter($"@WorkingId",queryId),
                    new SqlParameter($"@TotalCountFromPc", totalCount.ToString())
                };
                int count = SqlHelper.ExecuteNonQuery(sql, updateParameters.ToArray());
                if (count < 0)
                {
                    result.State = false;
                    result.Message = $"数据库操作失败";
                }
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 通过界面来保存报警信息设置. 所有的报警信息都是根据报警序号,从这个库里面获取的
        /// 一个报警序号代表一个报警类别
        /// </summary>
        /// <param name="alarmSetting"></param>
        /// <returns></returns>
        internal static DataResult SaveAlarmSetting(List<AlarmSettingModel> alarmSettingList)
        {
            DataResult result = new DataResult();
            string tableName = TableNames.AlarmSettingTb;
            try
            {
                // 1. 先删除表中内容
                string sqlDelete = $"Truncate Table {tableName} ";
                SqlHelper.ExecuteNonQuery(sqlDelete, null);
                // 2. 插入表中数据
                string sqlInsert = $"INSERT INTO [DBO].{tableName} ([AlarmCode], [Content],[SolutionHelp]) " +
                        $"VALUES (@AlarmCode,@Content,@SolutionHelp);";

                foreach (var alarmEntity in alarmSettingList)
                {
                    SqlParameter[] parameters = new SqlParameter[]
                    {
                        new SqlParameter("@AlarmCode",SqlDbType.VarChar){Value= alarmEntity.AlarmCode},
                        new SqlParameter("@Content",SqlDbType.VarChar){Value=alarmEntity.Content},
                        new SqlParameter("@SolutionHelp",SqlDbType.VarChar){Value=alarmEntity.SolutionHelp}
                    };
                    int ret = SqlHelper.ExecuteNonQuery(sqlInsert, parameters);
                    if (ret <= 0)
                    {
                        result.Message = $"数据表{tableName}插入数据失败!";
                        return result;
                    }
                }
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 保存汇总数据,直接插入就行.
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        internal static void SaveSummaryData(List<string> dataInsert)
        {
            string tableName = TableManager.GetTableNameByCrystalNumber(GlobalValues.CrystalNumberCurrent!);
            try
            {
                string sql = $"INSERT INTO {tableName} (DetectedTime,ProductionDate, WaferId, CutNumber, CrystalNumber, PositionNumber, ProductionLot, FlowerNumber, DetectionRecipe, DetectedLevel, LevelType, " +
                    $"TypeDescription, BoxNumber, ThicknessAver, TTV, LineTraceMax, Warping, ThicknessMin, ThicknessMax, IsDenseLine, LineTraceUpNum, LineTraceUpMax," +
                    $" LineTraceDownNum, LineTraceDownMax, LineTraceCount, ResistivityAver, ResistivityMax, ResistivityMin, LengthMax, LengthMin, LengthX, LengthY, DiagonalLeftStart, " +
                    $"DialonalRightStart, ChamferMax, ChamferMin, UpDownParallel, LeftRightParallel, SquareLineMax, SquareLineMin, VerticalAngleMax, VerticalAngleMin, LeftTopCharmfer, " +
                    $"RightTopCharmfer, LeftBottomCharmfer, RightBottomCharmfer, LeftTopAngle, RightTopAngle, LeftBottomAngle, RightBottomAngle,LengthXMax,LengthXMin,LengthYMax,LengthYMin," +
                    $"FrontEdgeBreakExist, FrontEdgeBreakNum, FrontEdgeBreakArea," +
                    $"BackEdgeBreakExist, BackEdgeBreakNum, BackEdgeBreakArea,LeftEdgeBreakExist, LeftEdgeBreakNum, LeftSurfaceBreakNum, LeftSurfaceBreakExist, RightEdgeBreakExist, " +
                    $"RightEdgeBreakNum, RightSurfaceBreakNum, " +
                    $"RightSurfaceBreakExist,SumdgeUpExist,SmudgeUpArea,SumdgeUpNum,SumdgeUpReverse,SumdgeUpHoleExist,SumdgeUpHoleNum,HoleExistUp,HoleNumUp,SumdgeDownExist," +
                    $"SumdgeDownArea,SumdgeDownNum,SumdgeDownReverse,SumdgeDownHoleExist,SumdgeDownHoleNum,HoleExistDown,HoleNumDown, SubfissureArea01, " +
                    $"SubfissureNum01, SubfissureExist01, SubfissureBreakArea01, SubfissureBreakNum01, SubfissureBreakExist01, SubfissureHoleNum01, SubfissureHoleExist01, SubfissureArea02, " +
                    $"SubfissureNum02, SubfissureExist02, SubfissureBreakArea02, SubfissureBreakNum02, SubfissureBreakExist02, SubfissureHoleNum02, SubfissureHoleExist02) " +
                    $"VALUES (@DetectedTime,@ProductionDate, @WaferId, @CutNumber, @CrystalNumber, @PositionNumber, @ProductionLot, @FlowerNumber, @DetectionRecipe, @DetectedLevel, @LevelType, " +
                    $"@TypeDescription, @BoxNumber, @ThicknessAver, @TTV, @LineTraceMax, @Warping, @ThicknessMin, @ThicknessMax, @IsDenseLine, @LineTraceUpNum, @LineTraceUpMax, " +
                    $"@LineTraceDownNum, @LineTraceDownMax, @LineTraceCount, @ResistivityAver, @ResistivityMax, @ResistivityMin, @LengthMax, @LengthMin, @LengthX, @LengthY, @DiagonalLeftStart, " +
                    $"@DialonalRightStart, @ChamferMax, @ChamferMin, @UpDownParallel, @LeftRightParallel, @SquareLineMax, @SquareLineMin, @VerticalAngleMax, @VerticalAngleMin, @LeftTopCharmfer, " +
                    $"@RightTopCharmfer, @LeftBottomCharmfer, @RightBottomCharmfer, @LeftTopAngle, @RightTopAngle, @LeftBottomAngle, @RightBottomAngle,@LengthXMax,@LengthXMin,@LengthYMax,@LengthYMin," +
                    $" @FrontEdgeBreakExist, @FrontEdgeBreakNum, @FrontEdgeBreakArea," +
                    $"@BackEdgeBreakExist, @BackEdgeBreakNum,@BackEdgeBreakArea, @LeftEdgeBreakExist, @LeftEdgeBreakNum, @LeftSurfaceBreakNum, @LeftSurfaceBreakExist, @RightEdgeBreakExist," +
                    $" @RightEdgeBreakNum, @RightSurfaceBreakNum," +
                    $"@RightSurfaceBreakExist, " +
                    $"@SumdgeUpExist,@SmudgeUpArea,@SumdgeUpNum,@SumdgeUpReverse,@SumdgeUpHoleExist,@SumdgeUpHoleNum,@HoleExistUp,@HoleNumUp," +
                    $"@SumdgeDownExist,@SumdgeDownArea,@SumdgeDownNum,@SumdgeDownReverse,@SumdgeDownHoleExist,@SumdgeDownHoleNum,@HoleExistDown,@HoleNumDown," +
                    $" @SubfissureArea01, @SubfissureNum01, " +
                    $"@SubfissureExist01, @SubfissureBreakArea01, @SubfissureBreakNum01, @SubfissureBreakExist01, @SubfissureHoleNum01, @SubfissureHoleExist01, @SubfissureArea02, @SubfissureNum02, " +
                    $"@SubfissureExist02, @SubfissureBreakArea02, @SubfissureBreakNum02, @SubfissureBreakExist02, @SubfissureHoleNum02, @SubfissureHoleExist02);";

                SqlParameter[] parameters = new SqlParameter[]
                {
                    new SqlParameter("@DetectedTime", SqlDbType.VarChar) { Value =  dataInsert[0]}, // 0
                    new SqlParameter("@ProductionDate",SqlDbType.VarChar){Value = dataInsert[1]}, // 1
                    new SqlParameter("@WaferId", SqlDbType.VarChar) { Value = dataInsert[2] }, // 2
                    new SqlParameter("@CutNumber", SqlDbType.VarChar) { Value = dataInsert[3]}, // 3
                    new SqlParameter("@CrystalNumber", SqlDbType.VarChar) { Value=dataInsert[4] }, // 4
                    new SqlParameter("@PositionNumber", SqlDbType.VarChar) { Value =dataInsert[5]}, // 5
                    new SqlParameter("@ProductionLot", SqlDbType.VarChar) { Value =dataInsert[6]}, // 6
                    new SqlParameter("@FlowerNumber", SqlDbType.VarChar) { Value = dataInsert[7] }, // 7
                    new SqlParameter("@DetectionRecipe", SqlDbType.VarChar) { Value =dataInsert[8] }, // 8
                    new SqlParameter("@DetectedLevel", SqlDbType.VarChar) { Value =dataInsert[9]}, // 9
                    new SqlParameter("@LevelType", SqlDbType.VarChar) { Value = dataInsert[10] },   // 10
                    new SqlParameter("@TypeDescription", SqlDbType.VarChar) { Value = dataInsert[11] }, // 11
                    new SqlParameter("@BoxNumber", SqlDbType.VarChar) { Value = dataInsert[12] }, // 12
                    new SqlParameter("@ThicknessAver", SqlDbType.VarChar) { Value = dataInsert[13]}, // 13
                    new SqlParameter("@TTV", SqlDbType.VarChar) { Value = dataInsert[14] },                 // 14
                    new SqlParameter("@LineTraceMax", SqlDbType.VarChar) { Value = dataInsert[15] }, // 15
                    new SqlParameter("@Warping", SqlDbType.VarChar) { Value = dataInsert[16] },      // 16
                    new SqlParameter("@ThicknessMin", SqlDbType.VarChar) { Value =dataInsert[60] }, // 60
                    new SqlParameter("@ThicknessMax", SqlDbType.VarChar) { Value = dataInsert[61]}, // 61
                    new SqlParameter("@IsDenseLine", SqlDbType.VarChar) { Value = dataInsert[62] }, // 62
                    new SqlParameter("@LineTraceUpNum", SqlDbType.VarChar) { Value = dataInsert[63]}, // 63
                    new SqlParameter("@LineTraceUpMax", SqlDbType.VarChar) { Value = dataInsert[64] }, // 64
                    new SqlParameter("@LineTraceDownNum", SqlDbType.VarChar) { Value = dataInsert[65] }, // 65
                    new SqlParameter("@LineTraceDownMax", SqlDbType.VarChar) { Value = dataInsert[66] }, // 66
                    new SqlParameter("@LineTraceCount", SqlDbType.VarChar) { Value = dataInsert[67] },       // 67
                    new SqlParameter("@ResistivityAver", SqlDbType.VarChar) { Value = dataInsert[17] }, // 17
                    new SqlParameter("@ResistivityMax", SqlDbType.VarChar) { Value = dataInsert[18] }, // 18
                    new SqlParameter("@ResistivityMin", SqlDbType.VarChar) { Value = dataInsert[19] }, // 19

                    new SqlParameter("@LengthMax", SqlDbType.VarChar) { Value = dataInsert[24] }, // 24
                    new SqlParameter("@LengthMin", SqlDbType.VarChar) { Value = dataInsert[25] }, // 25
                    new SqlParameter("@LengthX", SqlDbType.VarChar) { Value = dataInsert[26] }, // 26
                    new SqlParameter("@LengthY", SqlDbType.VarChar) { Value = dataInsert[27] }, // 27
                    new SqlParameter("@DiagonalLeftStart", SqlDbType.VarChar) { Value = dataInsert[28] }, // 28
                    new SqlParameter("@DialonalRightStart", SqlDbType.VarChar) { Value =dataInsert[29] }, // 29
                    new SqlParameter("@ChamferMax", SqlDbType.VarChar) { Value =dataInsert[30] }, // 30
                    new SqlParameter("@ChamferMin", SqlDbType.VarChar) { Value =dataInsert[31] }, // 31
                    new SqlParameter("@UpDownParallel", SqlDbType.VarChar) { Value = dataInsert[32] }, // 32
                    new SqlParameter("@LeftRightParallel", SqlDbType.VarChar) { Value = dataInsert[33] }, // 33
                    new SqlParameter("@SquareLineMax", SqlDbType.VarChar) { Value =dataInsert[34] }, // 34
                    new SqlParameter("@SquareLineMin", SqlDbType.VarChar) { Value = dataInsert[35] }, // 35
                    new SqlParameter("@VerticalAngleMax", SqlDbType.VarChar) { Value = dataInsert[36] }, // 36
                    new SqlParameter("@VerticalAngleMin", SqlDbType.VarChar) { Value =dataInsert[37] }, // 37
                    new SqlParameter("@LeftTopCharmfer", SqlDbType.VarChar) { Value = dataInsert[38] }, // 38
                    new SqlParameter("@RightTopCharmfer", SqlDbType.VarChar) { Value = dataInsert[39] }, // 39
                    new SqlParameter("@LeftBottomCharmfer", SqlDbType.VarChar) { Value = dataInsert[40] }, // 40
                    new SqlParameter("@RightBottomCharmfer", SqlDbType.VarChar) { Value = dataInsert[41] }, // 41
                    new SqlParameter("@LeftTopAngle", SqlDbType.VarChar) { Value =dataInsert[42] }, // 42
                    new SqlParameter("@RightTopAngle", SqlDbType.VarChar) { Value =dataInsert[43] }, // 43
                    new SqlParameter("@LeftBottomAngle", SqlDbType.VarChar) { Value = dataInsert[44] }, // 44
                    new SqlParameter("@RightBottomAngle", SqlDbType.VarChar) { Value = dataInsert[45]}, // 45

                    new SqlParameter("@LengthXMax", SqlDbType.VarChar) { Value = dataInsert[20]}, // 20
                    new SqlParameter("@LengthXMin", SqlDbType.VarChar) { Value = dataInsert[21] }, // 21
                    new SqlParameter("@LengthYMax", SqlDbType.VarChar) { Value = dataInsert[22]}, // 22
                    new SqlParameter("@LengthYMin", SqlDbType.VarChar) { Value = dataInsert[23]}, // 23

                    new SqlParameter("@FrontEdgeBreakExist", SqlDbType.VarChar) { Value =dataInsert[46]}, // 46
                    new SqlParameter("@FrontEdgeBreakNum", SqlDbType.VarChar) { Value = dataInsert[47]}, // 47
                    new SqlParameter("@FrontEdgeBreakArea", SqlDbType.VarChar) { Value = dataInsert[48]}, // 48
                    new SqlParameter("@BackEdgeBreakExist", SqlDbType.VarChar) { Value = dataInsert[49]},// 49
                    new SqlParameter("@BackEdgeBreakNum", SqlDbType.VarChar) { Value = dataInsert[50]}, // 50
                    new SqlParameter("@BackEdgeBreakArea", SqlDbType.VarChar) { Value = dataInsert[51]}, // 51

                    new SqlParameter("@LeftEdgeBreakNum", SqlDbType.VarChar) { Value = dataInsert[52]}, // 52
                    new SqlParameter("@LeftEdgeBreakExist", SqlDbType.VarChar) { Value = dataInsert[53]}, // 53
                    new SqlParameter("@LeftSurfaceBreakNum", SqlDbType.VarChar) { Value = dataInsert[54] }, // 54
                    new SqlParameter("@LeftSurfaceBreakExist", SqlDbType.VarChar) { Value = dataInsert[55]}, // 55

                    new SqlParameter("@RightEdgeBreakNum", SqlDbType.VarChar) { Value = dataInsert[56]}, // 56
                    new SqlParameter("@RightEdgeBreakExist", SqlDbType.VarChar) { Value = dataInsert[57]}, // 57
                    new SqlParameter("@RightSurfaceBreakNum", SqlDbType.VarChar) { Value = dataInsert[58]}, // 58
                    new SqlParameter("@RightSurfaceBreakExist", SqlDbType.VarChar) { Value = dataInsert[59]}, // 59


                    new SqlParameter("@SumdgeUpExist", SqlDbType.VarChar) { Value = dataInsert[68]}, // 68
                    new SqlParameter("@SmudgeUpArea", SqlDbType.VarChar) { Value = dataInsert[69]}, // 69
                    new SqlParameter("@SumdgeUpNum", SqlDbType.VarChar) { Value = dataInsert[70]}, // 70
                    new SqlParameter("@SumdgeUpReverse",SqlDbType.VarChar){Value = dataInsert[71] }, // 71
                    new SqlParameter("@HoleExistUp", SqlDbType.VarChar) { Value = dataInsert[72]}, // 缺口有无 72
                    new SqlParameter("@SumdgeUpHoleExist", SqlDbType.VarChar) { Value = dataInsert[73]}, // 穿孔有无 73
                    new SqlParameter("@SumdgeUpHoleNum", SqlDbType.VarChar) { Value = "0"}, // 无数据,默认是0
                    new SqlParameter("@HoleNumUp", SqlDbType.VarChar) { Value = "0"}, // 无数据,默认是0

                    new SqlParameter("@SumdgeDownExist", SqlDbType.VarChar) { Value= dataInsert[74]}, // 74
                    new SqlParameter("@SumdgeDownArea", SqlDbType.VarChar) { Value = dataInsert[75]}, // 75
                    new SqlParameter("@SumdgeDownNum", SqlDbType.VarChar) { Value = dataInsert[75]}, // 76
                    new SqlParameter("@SumdgeDownReverse",SqlDbType.VarChar){Value = dataInsert[77]}, // 77
                    new SqlParameter("@HoleExistDown", SqlDbType.VarChar) { Value = dataInsert[78]}, // 78
                    new SqlParameter("@SumdgeDownHoleExist", SqlDbType.VarChar) { Value = dataInsert[79]}, // 79
                    new SqlParameter("@SumdgeDownHoleNum", SqlDbType.VarChar) { Value = "0"},// 无数据,默认是0
                    new SqlParameter("@HoleNumDown", SqlDbType.VarChar) { Value = "0"}, // 无数据,默认是0

                    new SqlParameter("@SubfissureExist01", SqlDbType.VarChar) { Value = dataInsert[80]}, // 80
                    new SqlParameter("@SubfissureArea01", SqlDbType.VarChar) { Value = dataInsert[81]}, // 81
                    new SqlParameter("@SubfissureNum01", SqlDbType.VarChar) { Value = dataInsert[81]}, // 82
                    new SqlParameter("@SubfissureBreakExist01", SqlDbType.VarChar) { Value = dataInsert[83]}, // 83
                    new SqlParameter("@SubfissureBreakArea01", SqlDbType.VarChar) { Value = dataInsert[84]} , // 84
                    new SqlParameter("@SubfissureBreakNum01", SqlDbType.VarChar) { Value = dataInsert[85]}, // 85
                    new SqlParameter("@SubfissureHoleExist01", SqlDbType.VarChar) { Value = dataInsert[86]}, // 86
                    new SqlParameter("@SubfissureHoleNum01", SqlDbType.VarChar) { Value = dataInsert[87]}, // 87

                    new SqlParameter("@SubfissureExist02", SqlDbType.VarChar) { Value = dataInsert[88]}, // 88
                    new SqlParameter("@SubfissureArea02", SqlDbType.VarChar) { Value = dataInsert[89]}, // 89
                    new SqlParameter("@SubfissureNum02", SqlDbType.VarChar) { Value = dataInsert[90]}, // 90
                    new SqlParameter("@SubfissureBreakExist02", SqlDbType.VarChar) { Value = dataInsert[91]}, // 91
                    new SqlParameter("@SubfissureBreakArea02", SqlDbType.VarChar) { Value = dataInsert[92]}, // 92
                    new SqlParameter("@SubfissureBreakNum02", SqlDbType.VarChar) { Value = dataInsert[93]}, // 93
                    new SqlParameter("@SubfissureHoleExist02", SqlDbType.VarChar) { Value = dataInsert[94]}, // 94
                    new SqlParameter("@SubfissureHoleNum02", SqlDbType.VarChar) { Value = dataInsert[95]}, // 95
                };
                //这里插入数据是用来测试,正常生产部需要插入数据.
                int ret = SqlHelper.ExecuteNonQuery(sql, parameters);
                string infoMessage;
                if (ret <= 0)
                {
                    infoMessage = $"数据表{tableName} 插入数据失败!";
                    LogHelper.WriteLog(LogType.Info, infoMessage);
                    throw new Exception(infoMessage);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"{tableName} 数据表创建失败: {ex.Message}");
            }
        }
    }
}
